如何与FileResult在ASP.NET MVC RC1返回304状态 [英] How return 304 status with FileResult in ASP.NET MVC RC1

查看:388
本文介绍了如何与FileResult在ASP.NET MVC RC1返回304状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如你可能知道,我们已经有了一个新的的ActionResult 名为 FileResult 在ASP.NET MVC的RC1版本。

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 return image to browser dynamically. Something like this:

public ActionResult DisplayPhoto(int id)
{
   Photo photo = GetPhotoFromDatabase(id);
   return File(photo.Content, photo.ContentType);
}

在HTML code,我们可以用这样的:

In the HTML code, we can use something like this:

<img src="http://mysite.com/controller/DisplayPhoto/657">

由于图像是动态返回,我们需要一种方法来缓存返回的流,使我们不必从数据库再次读取的图像。我想我们可以像这样做,我不知道:

Since the image is returned dynamically, we need a way to cache the returned stream so that we don't need to read the image again from database. I guess we can do it with something like this, I'm not sure:

Response.StatusCode = 304;

这告诉你已经有图像缓存浏览器。我只是不知道在我的操作方法的返回状态code设置为304后,我应该返回null或什么?

This tells the browser that you already have the image in your cache. I just don't know what to return in my action method after setting StatusCode to 304. Should I return null or something?

推荐答案

本博客回答了这个问题对我来说; <一href=\"http://weblogs.asp.net/jeff/archive/2009/07/01/304-your-images-from-a-database.aspx\">http://weblogs.asp.net/jeff/archive/2009/07/01/304-your-images-from-a-database.aspx

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

基本上,你需要阅读的请求头,比较上次修改的日期,并返回304,如果他们匹配,否则返回图像(200状态),并设置适当的缓存头。

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片断:

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

这篇关于如何与FileResult在ASP.NET MVC RC1返回304状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆