2015-06-27 75 views
0

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

回答

1

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

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

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

0

这个SO answer似乎有你所需要的。它使用控制器上的File方法返回具有文件内容的FileContentResult。