簡體   English   中英

ASP.NET MVC-返回純圖像數據與視圖

[英]ASP.NET MVC - Return Pure Image Data vs View

我有一個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”,我想返回純數據。 這樣,其他開發人員可以將照片包含在他們的頁面中。 我的問題是,我該怎么做?

您可以將圖像簡單地作為文件返回。 像這樣:

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

本質上File()方法返回原始文件作為結果。

這樣的答案似乎滿足您的需求。 它使用控制器上的File方法返回具有文件內容的FileContentResult。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM