chemitaxis
chemitaxis

Reputation: 14889

Application_PreSendRequestHeaders and Application_BeginRequest in ASP.NET MVC 6 (ASP.NET 5)

How can I use these methods in ASP.NET 5 (MVC6). In MVC5, I used it in Global.asax... and now? Startup class maybe?

protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            app?.Context?.Response.Headers.Remove("Server");
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (this.Request.Url.Host.StartsWith("www") || this.Request.Url.IsLoopback) return;
            var url = new UriBuilder(this.Request.Url) { Host = "www." + this.Request.Url.Host };
            this.Response.RedirectPermanent(url.ToString(), endResponse: true);
        }

Thanks!

Upvotes: 3

Views: 7907

Answers (1)

Stafford Williams
Stafford Williams

Reputation: 9806

Middleware!

public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory)
{
    app.Use(next => async context =>
    {
        context.Response.Headers.Remove("Server");
        await next.Invoke(context);
    });

    app.Use(next => async context => {
        if (context.Request.Path.ToString().StartsWith("www"))
            await next.Invoke(context);
        else
            context.Response.Redirect("www" + context.Request.Path.ToString());
    });
}

Here's a good tutorial.

Upvotes: 5

Related Questions