.net Owin 自主机,无缓存

.net Owin Self host with with no caching

我有一个 OWIN self-host 应用程序,用于提供一个简单的开发 Web 服务器来为 single-page HTML 应用程序提供服务。由于我在外部编辑 javascript,我想告诉服务器发回立即过期的缓存 headers(以防止 Chrome 缓存)。

我需要在我的启动中添加什么(注意此服务器启用了文件浏览)。

   class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var hubConfiguration = new HubConfiguration();
            hubConfiguration.EnableDetailedErrors = (Tools.DebugLevel > 10);
            hubConfiguration.EnableJavaScriptProxies = true;
            app.UseCors(CorsOptions.AllowAll);
            //app.UseStaticFiles();
            app.UseFileServer(new FileServerOptions()
            {
                //RequestPath = new PathString("/Scopes"),
                EnableDirectoryBrowsing = true,
                FileSystem = new PhysicalFileSystem(@".\Scopes"),
            });
            app.MapSignalR("/signalr", hubConfiguration);
        }
    }

在 Microsoft asp 论坛中获得了一些帮助:

https://forums.asp.net/p/2094446/6052100.aspx?p=True&t=635990766291814480

这是我所做的并且效果很好:我在启动中添加了以下行:

app.Use(typeof(MiddleWare));

...

class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var hubConfiguration = new HubConfiguration();
        hubConfiguration.EnableDetailedErrors = (Tools.DebugLevel > 10);
        hubConfiguration.EnableJavaScriptProxies = true;
        app.UseCors(CorsOptions.AllowAll);
        //app.UseStaticFiles();
        app.Use(typeof(MiddleWare));
        app.UseFileServer(new FileServerOptions()
        {
            //RequestPath = new PathString("/Scopes"),
            EnableDirectoryBrowsing = true,
            FileSystem = new PhysicalFileSystem(@".\Scopes"),
        });
        app.MapSignalR("/signalr", hubConfiguration);
    }
}

然后我定义了我的中间件:

using Microsoft.Owin;
using System.Threading.Tasks;

namespace Gateway
{
    class MiddleWare : OwinMiddleware
    {
        public MiddleWare(OwinMiddleware next)
        : base(next)
        {
        }
        public override async Task Invoke(IOwinContext context)
        {
            context.Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
            context.Response.Headers["Pragma"] = "no-cache";
            context.Response.Headers["Expires"] = "0";
            await Next.Invoke(context);
        }
    }
}

比新中间件更简单的是像这样在 FileServerOptions 中使用 StaticFileOptions

options.StaticFileOptions.OnPrepareResponse = context =>
{
     context.OwinContext.Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
     context.OwinContext.Response.Headers["Pragma"] = "no-cache";
     context.OwinContext.Response.Headers["Expires"] = "0";
};