ASP.NET MVC : how do I return 304 "Not Modified" status?
Asked Answered
C

3

20

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 "Not Modified" from action;
  2. include "Last-Modified" time stamp in the response.

I use return Content('my data'); for action result.

Basically I want an easy way to do what is talked about in this article : http://weblogs.asp.net/jeff/archive/2009/07/01/304-your-images-from-a-database.aspx

Comprehension answered 27/4, 2011 at 20:14 Comment(1)
Similar Q&A for .NET core can be found in this questionInfamous
R
17

(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");
Rumal answered 20/9, 2012 at 21:36 Comment(0)
S
10

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.

Sabu answered 27/4, 2011 at 20:38 Comment(3)
too much typing. I am hopeful there is a built way to do that, something like : return NotModified(myResource.LastModified);Comprehension
more importantly I still need to check and parse "If-Modified-Since" in request, and that's become too complex for me.Comprehension
"'Not Modified' Filter." link is brokenMccauley
L
1

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);
Lowpitched answered 26/8, 2016 at 9:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.