我希望我的静态内容(图像,javascript文件,css文件等)只有在文件更新后才能完全提供服务。
如果文件自上次请求以来没有更改(由ETag和Last-Modified响应标头值确定),那么我希望客户端浏览器使用这些文件的缓存版本。
Nancy是否支持此功能?
发布于 2012-11-09 18:41:55
Nancy确实部分支持ETag和Last-Modified报头。它为所有静态文件设置这些值,但从0.13版本开始,它不会对这些值做任何操作。下面是Nancy代码:
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;
}要使用ETag和Last-Modified标头值,您需要添加两个修改过的扩展方法。我直接借用了GitHub中的Nancy源代码(因为此功能计划在未来的版本中使用),但最初的想法来自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;
}
}最后,您需要使用Nancy BootStrapper中的AfterRequest钩子调用这些方法。
BootStrapper
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状态代码下载该文件...诸若此类。
https://stackoverflow.com/questions/12726113
复制相似问题