2012-10-04 22 views

回答

14

南希确实部分支持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标头值的。我直接从GitHub上的南希源代码借来的这些(如该功能计划在将来的版本),但最初的想法来自西蒙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挂钩调用这些方法。

引导程序

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状态码...等等。