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

后端 未结 3 1470
無奈伤痛
無奈伤痛 2020-12-16 12:09

ASP.NET MVC 3.0, IIS 7, .NET 4

I have an action that returns data that seldom changes (almost static).

Is there an easy way to:

  1. return 304 \"
3条回答
  •  一生所求
    2020-12-16 12:48

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

提交回复
热议问题