简体   繁体   中英

ASP.NET MVC - Return Pure Image Data vs View

I have an ASP.NET MVC app. In this app, I have a Controller that looks like this:

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");
    }
  }
}

I am currently able to successfully hit the Photos route like I want. However, if the request includes "?pure=true" at the end, I want to return the pure data. This way another developer can include the photo in their page. My question is, how do I do this?

You can return the image as simply a file. Something like this:

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

Essentially the File() method returns a raw file as the result.

This SO answer appears to have what you need. It uses the File method on the controller to return a FileContentResult that has the file contents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM