开发者

Does it make sense to set Http Cache Headers on a 404 response?

I have a database that stores images which can be access via a primary key ID (vomit, I know, but it's out of my control).

I have a pretty standard Asp .net Mvc Controller that reads the database and if a row is found in the database it returns the image bytes as a FileResult. If a row is not found, I have a custom action result that sets the response status to 404. I do not throw an exception, but instead let IIS handle the 404 status and return a static file.

public class ContentMediaNotFoundResult : ActionResult
{
    public ContentMediaNotFoundResult() { }

    public override void ExecuteResult(ControllerContext context)
    {
        //-- H开发者_如何学Goere the only thing we are doing is setting the Response code to 404 and then we are   going to let IIS service the request
        //-- based on the settings in system.webServer/httpErrors (which may come from the root .config, so be careful)
        context.HttpContext.Response.StatusCode = 404;
    }
}

Recently, we were testing on Firefox v3.6.1 and were noticing the browser was making multiple requests (3 to be precise) for each image, hence our controller factory was being hit 3 times and going to the database 3 times from our action method. This behavior was only happneing from Firefox (IE, chrome were normal).

My question is, does it make sense to add Http Cache Headers to 404 responses in my ContentMediaNotFoundResult so that my action method doesn't hit the database continually.


Sure, you can set Cache headers for 404s. As @Darin mentioned, your cache aging may affect any issues with replacing a 404'd image, but that's the same problem with caching any object that may change.

Seems like only 5xx errors should probably not be cached, but 4xx are fine.


My view is that it depends. If you have a fast-changing Web API where a resource might be added any moment, then you'd want clients to always query the origin.

If you have a lot of content that doesn't change much, caching 404 might help alot.

Check this real-world example out:

http://highscalability.com/blog/2010/3/26/strategy-caching-404s-saved-the-onion-66-on-server-time.html


It doesn't make any sense to set cache headers on 404 pages because if later an image with this id added to the database the user would still be getting 404s. Maybe you should try to understand why does FireFox sends 3 requests to this url.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜