How return 304 status with FileResult in ASP.NET MVC RC1

前端 未结 3 1260
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 16:03

As you may know we have got a new ActionResult called FileResult in RC1 version of ASP.NET MVC.

Using that, your action methods can ret

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-05 16:37

    This blog answered the question for me; http://weblogs.asp.net/jeff/archive/2009/07/01/304-your-images-from-a-database.aspx

    Basically, you need to read the request header, compare the last modified dates and return 304 if they match, otherwise return the image (with a 200 status) and set the cache headers appropriately.

    Code snippet from the blog:

    public ActionResult Image(int id)
    {
        var image = _imageRepository.Get(id);
        if (image == null)
            throw new HttpException(404, "Image not found");
        if (!String.IsNullOrEmpty(Request.Headers["If-Modified-Since"]))
        {
            CultureInfo provider = CultureInfo.InvariantCulture;
            var lastMod = DateTime.ParseExact(Request.Headers["If-Modified-Since"], "r", provider).ToLocalTime();
            if (lastMod == image.TimeStamp.AddMilliseconds(-image.TimeStamp.Millisecond))
            {
                Response.StatusCode = 304;
                Response.StatusDescription = "Not Modified";
                return Content(String.Empty);
            }
        }
        var stream = new MemoryStream(image.GetImage());
        Response.Cache.SetCacheability(HttpCacheability.Public);
        Response.Cache.SetLastModified(image.TimeStamp);
        return File(stream, image.MimeType);
    }
    

提交回复
热议问题