2015-05-28 72 views
2

我有一個使用OWIN提供基本Web服務器的自託管應用程序。配置的關鍵部分是以下行:根據請求修改OWIN/Katana PhysicalFileSystem頁面

appBuilder.UseFileServer(new FileServerOptions { 
    FileSystem = new PhysicalFileSystem(filePath) 
}); 

這提供了filePath用於瀏覽列出的靜態文件,這多少是按預期工作。

但是我遇到了一個情況,我想稍微修改一個請求的基礎上的文件之一。特別是,我想從文件系統中加載文件的「正常」版本,根據傳入的Web請求的標題稍微改變它,然後將更改後的版本返回給客戶端而不是原始版本。所有其他文件應保持不變。

我如何去這樣做呢?

回答

1

好了,我不知道這是做這個方式,但它似乎工作:

internal class FileReplacementMiddleware : OwinMiddleware 
{ 
    public FileReplacementMiddleware(OwinMiddleware next) : base(next) {} 

    public override async Task Invoke(IOwinContext context) 
    { 
     MemoryStream memStream = null; 
     Stream httpStream = null; 
     if (ShouldAmendResponse(context)) 
     { 
      memStream = new MemoryStream(); 
      httpStream = context.Response.Body; 
      context.Response.Body = memStream; 
     } 

     await Next.Invoke(context); 

     if (memStream != null) 
     { 
      var content = await ReadStreamAsync(memStream); 
      if (context.Response.StatusCode == 200) 
      { 
       content = AmendContent(context, content); 
      } 
      var contentBytes = Encoding.UTF8.GetBytes(content); 
      context.Response.Body = httpStream; 
      context.Response.ETag = null; 
      context.Response.ContentLength = contentBytes.Length; 
      await context.Response.WriteAsync(contentBytes, context.Request.CallCancelled); 
     } 
    } 

    private static async Task<string> ReadStreamAsync(MemoryStream stream) 
    { 
     stream.Seek(0, SeekOrigin.Begin); 
     using (var reader = new StreamReader(stream, Encoding.UTF8)) 
     { 
      return await reader.ReadToEndAsync(); 
     } 
    } 

    private bool ShouldAmendResponse(IOwinContext context) 
    { 
     // logic 
    } 

    private string AmendContent(IOwinContext context, string content) 
    { 
     // logic 
    } 
} 

靜態文件中間件在什麼地方這對管道加入。