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

后端 未结 3 1471
無奈伤痛
無奈伤痛 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:46

    (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");
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-16 13:08

    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.

    0 讨论(0)
提交回复
热议问题