locked
Adding default header (CACHE-CONTROL:NO-CACHE) for OWIN self host RRS feed

  • Question

  • User127989590 posted

    I have a small C#, EXE which is used for grabbing sensor data. It uses Signalr to send the data. Then we found we wanted to also hold a few web pages for looking at the state of this server (it runs in a small box at a remote site) no big server, small footprint.

    But we have issues with the OWI, Self-Host caching the web pages. How can tell the Self-Host to add headers to all HTML & JS requests to stop caching. e.g. CACHE-CONTROL:NO-CACHE

    Here is what the current code is that sets it up:

    (web pages are stored in the \Scopes folder.

      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);
            }
        }

    Thursday, May 5, 2016 2:14 PM

Answers

  • User36583972 posted

    Hi Dr. YSG,

    You can try to add a  Custom Response Header in your web api. You can refer the following method.

    1: Define a CustomHeaderHandler class

     public class CustomHeaderHandler : DelegatingHandler
        {
            //using System.Net.Http; using System.Threading;using System.Threading.Tasks;
            async protected override Task<HttpResponseMessage> SendAsync(
                    HttpRequestMessage request, CancellationToken cancellationToken)
            {
                HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
                response.Headers.Add("CACHE-CONTROL", "NO-CACHE");
                return response;
            }
        }

    2: Configure Web API for self-host

    class Startup
        {
            // This code configures Web API. The Startup class is specified as a type
            // parameter in the WebApp.Start method.
            public void Configuration(IAppBuilder appBuilder)
            {
                //----
    
                // Configure Web API for self-host. 
                HttpConfiguration config = new HttpConfiguration();
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
                config.MessageHandlers.Add(new CustomHeaderHandler());
    
                appBuilder.UseWebApi(config);
                //------
            }
    
        }
    
    

    HTTP Message Handlers in ASP.NET Web API:

    http://www.asp.net/web-api/overview/advanced/http-message-handlers

    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, May 9, 2016 2:26 AM
  • User127989590 posted

    Here is what I do and it works great: I added the following line to the Startup:

    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);
            }
        }

    and then I defined my middleware:

    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);
            }
        }
    }
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 17, 2016 5:09 PM

All replies

  • User36583972 posted

    Hi Dr. YSG,

    You can try to add a  Custom Response Header in your web api. You can refer the following method.

    1: Define a CustomHeaderHandler class

     public class CustomHeaderHandler : DelegatingHandler
        {
            //using System.Net.Http; using System.Threading;using System.Threading.Tasks;
            async protected override Task<HttpResponseMessage> SendAsync(
                    HttpRequestMessage request, CancellationToken cancellationToken)
            {
                HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
                response.Headers.Add("CACHE-CONTROL", "NO-CACHE");
                return response;
            }
        }

    2: Configure Web API for self-host

    class Startup
        {
            // This code configures Web API. The Startup class is specified as a type
            // parameter in the WebApp.Start method.
            public void Configuration(IAppBuilder appBuilder)
            {
                //----
    
                // Configure Web API for self-host. 
                HttpConfiguration config = new HttpConfiguration();
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
                config.MessageHandlers.Add(new CustomHeaderHandler());
    
                appBuilder.UseWebApi(config);
                //------
            }
    
        }
    
    

    HTTP Message Handlers in ASP.NET Web API:

    http://www.asp.net/web-api/overview/advanced/http-message-handlers

    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, May 9, 2016 2:26 AM
  • User127989590 posted

    Here is what I do and it works great: I added the following line to the Startup:

    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);
            }
        }

    and then I defined my middleware:

    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);
            }
        }
    }
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 17, 2016 5:09 PM