首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NancyFX是否支持通过ETag和Last-Modified标头进行静态内容缓存?

NancyFX是否支持通过ETag和Last-Modified标头进行静态内容缓存?
EN

Stack Overflow用户
提问于 2012-10-04 19:19:40
回答 1查看 3K关注 0票数 10

我希望我的静态内容(图像,javascript文件,css文件等)只有在文件更新后才能完全提供服务。

如果文件自上次请求以来没有更改(由ETagLast-Modified响应标头值确定),那么我希望客户端浏览器使用这些文件的缓存版本。

Nancy是否支持此功能?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-09 18:41:55

Nancy确实部分支持ETagLast-Modified报头。它为所有静态文件设置这些值,但从0.13版本开始,它不会对这些值做任何操作。下面是Nancy代码:

代码语言:javascript
复制
if (IsSafeFilePath(rootPath, fullPath))
{
    Filename = Path.GetFileName(fullPath);

    var fi = new FileInfo(fullPath);
    // TODO - set a standard caching time and/or public?
    Headers["ETag"] = fi.LastWriteTimeUtc.Ticks.ToString("x");
    Headers["Last-Modified"] = fi.LastWriteTimeUtc.ToString("R");
    Contents = GetFileContent(fullPath);
    ContentType = contentType;
    StatusCode = HttpStatusCode.OK;
    return;
}

要使用ETagLast-Modified标头值,您需要添加两个修改过的扩展方法。我直接借用了GitHub中的Nancy源代码(因为此功能计划在未来的版本中使用),但最初的想法来自Simon Cropp - Conditional responses with NancyFX

扩展方法

代码语言:javascript
复制
public static void CheckForIfNonMatch(this NancyContext context)
{
    var request = context.Request;
    var response = context.Response;

    string responseETag;
    if (!response.Headers.TryGetValue("ETag", out responseETag)) return;
    if (request.Headers.IfNoneMatch.Contains(responseETag))
    {
        context.Response = HttpStatusCode.NotModified;
    }
}

public static void CheckForIfModifiedSince(this NancyContext context)
{
    var request = context.Request;
    var response = context.Response;

    string responseLastModified;
    if (!response.Headers.TryGetValue("Last-Modified", out responseLastModified)) return;
    DateTime lastModified;

    if (!request.Headers.IfModifiedSince.HasValue || !DateTime.TryParseExact(responseLastModified, "R", CultureInfo.InvariantCulture, DateTimeStyles.None, out lastModified)) return;
    if (lastModified <= request.Headers.IfModifiedSince.Value)
    {
        context.Response = HttpStatusCode.NotModified;
    }
}

最后,您需要使用Nancy BootStrapper中的AfterRequest钩子调用这些方法。

BootStrapper

代码语言:javascript
复制
public class MyBootstrapper :DefaultNancyBootstrapper
{
    protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
    {
        pipelines.AfterRequest += ctx =>
        {
            ctx.CheckForIfNoneMatch();
            ctx.CheckForIfModifiedSince();
        };
        base.ApplicationStartup(container, pipelines);
    }
    //more stuff
}

观察Fiddler的响应,您将看到静态文件的第一次命中下载,并带有200 - OK状态码。

此后,每个请求都会返回一个304 - Not Modified状态代码。更新文件后,再次请求该文件将使用200 - OK状态代码下载该文件...诸若此类。

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12726113

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档