ASP.NET MVC-返回纯图像数据与视图

本文关键字:数据 视图 图像 NET MVC- 返回 ASP | 更新日期: 2023-09-27 18:00:10

我有一个ASP.NET MVC应用程序。在这个应用程序中,我有一个控制器,看起来像这样:

public class MyController 
{
  public ActionResult Index() 
  {
    return View();
  }
  public ActionResult Photos(int id)
  {
    bool usePureImage = false;
    if (String.IsNullOrEmpty(Request.QueryString["pure"]) == false)
    {
      Boolean.TryParse(Request.QueryString["pure"], out usePureImage);
    }
    if (usePureImage)
    {
      // How do I return raw image/file data here?
    }
    else
    {
      ViewBag.PictureUrl = "app/photos/" + id + ".png";
      return View("Picture");
    }
  }
}

我目前能够像我想要的那样成功地点击照片路线。但是,如果请求的末尾包含"?pure=true",我希望返回纯数据。通过这种方式,另一个开发人员可以将照片包含在他们的页面中。我的问题是,我该怎么做?

ASP.NET MVC-返回纯图像数据与视图

您可以简单地将图像作为文件返回。类似这样的东西:

var photosDirectory = Server.MapPath("app/photos/");
var photoPath = Path.Combine(photosDirectory, id + ".png");
return File(photoPath, "image/png");

从本质上讲,File()方法返回一个原始文件作为结果。

这个SO答案似乎符合您的需求。它使用控制器上的File方法返回具有文件内容的FileContentResult。