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

时间:2015-06-27 17:41:44

标签: c# asp.net-mvc

我有一个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”,我想返回纯数据。这样,另一位开发人员可以在他们的页面中包含照片。我的问题是,我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以将图像作为文件返回。像这样:

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

基本上the File() method返回原始文件作为结果。

答案 1 :(得分:0)

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