ASP.NET MVC : how do I return 304 “Not Modified” status?

情到浓时终转凉″ 提交于 2019-11-29 03:08:47

(Very!) late answer but this question pops up near the top in search engine results so it might be useful to future people landing here.

Alternative for part 1:

return new HttpStatusCodeResult(304, "Not Modified");

Whats wrong with this for 304?

        Response.StatusCode = 304;
        Response.StatusDescription = "Not Modified";
        return Content(String.Empty);

and this for LastModified:

        Response.Cache.SetLastModified(DateTime.Now);

Or maybe just create a 'Not Modified' Filter.

use the material provided, you can build a small utility function in your controller

protected bool CheckStatus304(DateTime lastModified)
{
    //http://weblogs.asp.net/jeff/304-your-images-from-a-database
    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 == lastModified.AddMilliseconds(-lastModified.Millisecond))
        {
            Response.StatusCode = 304;
            Response.StatusDescription = "Not Modified";
            return true;
        }
    }

    Response.Cache.SetCacheability(HttpCacheability.Public);
    Response.Cache.SetLastModified(lastModified);

    return false;
}

then use it like this:

if (CheckStatus304(image.CreatedDate)) return Content(string.Empty);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!