gpt4 book ai didi

browser-cache - NancyFX 是否支持通过 ETag 和 Last-Modified header 进行静态内容缓存?

转载 作者:行者123 更新时间:2023-12-04 03:29:18 26 4
gpt4 key购买 nike

我希望我的静态内容(图像、javascript 文件、css 文件等)仅在文件更新后才能完整提供。

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

Nancy 是否支持此功能?

最佳答案

Nancy 确实部分支持 ETagLast-Modified标题。它为所有静态文件设置它们,但从版本 开始0.13 它对这些值没有任何作用。这是南希代码:

Nancy.Responses.GenericFileResponse.cs

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您需要添加一些修改后的扩展方法的 header 值。我直接从 GitHub 的 Nancy 源代码中借用了这些(因为这个功能计划在 future 发布),但最初的想法来自 Simon Cropp - Conditional responses with NancyFX

扩展方法
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;
}
}

最后,您需要使用 AfterRequest 调用这些方法。卡在你的 Nancy BootStrapper 中。

Bootstrap
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 下载它。状态码...等等。

关于browser-cache - NancyFX 是否支持通过 ETag 和 Last-Modified header 进行静态内容缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12726113/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com