3

I'm upgrading my WebApi(s) to MVC6.

In WebApi I could intercept every HTTP request and if it was a preflight I could respond with headers the browser would accept.

I'm trying to figure out how to do the same thing in MVC6 WebApi.

Here is the WebApi code.

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (Context.Request.Path.Contains("api/") && Context.Request.HttpMethod == "OPTIONS")
        {
            Context.Response.AddHeader("Access-Control-Allow-Origin", Context.Request.Headers["Origin"]);
            Context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            Context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
            Context.Response.End();
        }
    } 

How do I do the same thing with MVC6?

Thanks, Bob

Here is my next attempt based on feedback. I could probably figure this out on my own if I understood the middleware pipeline. I'll learn it now of course.

I tried this code but it's not hit on http requests as I had hoped.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // Configure the HTTP request pipeline.
        app.UseStaticFiles();

        // Add MVC to the request pipeline.
        app.UseMvc();
        // Add the following route for porting Web API 2 controllers.
        // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");

        // custom middleware to checked each call as it comes in.
        app.Use(async (httpContext, next) =>
        {
            if (httpContext.Request.Path.Value.Contains("api/") && httpContext.Request.Method == "OPTIONS")
            {
                httpContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { httpContext.Request.Headers["Origin"] });
                httpContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept" });
                httpContext.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" });
                httpContext.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });
                return;
            }
            await next();
        });

    }
user3448990
  • 323
  • 6
  • 15
  • duplicate with http://stackoverflow.com/questions/31976337/mvc6-cors-intercept-preflight – Avlin Oct 08 '15 at 23:52

1 Answers1

3

You can add your own middleware for that. Here is a quick example adding it inline, but you could also encapsulate in a class:

app.Use(async (httpContext, next) =>
{
    if (httpContext.Request.Path.Value.Contains("api/") && httpContext.Request.Method == "OPTIONS")
    {
        httpContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { httpContext.Request.Headers["Origin"] });
        httpContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept" });
        httpContext.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" });
        httpContext.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });
        return;
    }
    await next();
});

You will probably also want to keep an eye on the ongoing work to support cors within the ASP 5 framework

Community
  • 1
  • 1
Daniel J.G.
  • 34,266
  • 9
  • 112
  • 112
  • Thanks Daniel. I'll try this out today. And thanks for the additional "ongoing work" resource. I'll keep an eye on that. – user3448990 Aug 13 '15 at 13:16
  • 1
    That works. Right now IIS is hijacking the Options preflight. In Web Api that was easy to overcome with a WebConfig change. Now we don't have WebConfig... Or do we? Hmmm. I'll be back. – user3448990 Aug 13 '15 at 23:47
  • There is still a web.config in the wwwroot folder, I would expect the settings for IIS in that file to keep working (Something like [this deployment](http://stackoverflow.com/questions/27325264/asp-net-5-project-hosting-on-iis)), but I have only tried IIS express myself. – Daniel J.G. Aug 14 '15 at 07:32
  • 4 years and 8 mos later I found this response and it helped me out BIG time. Intercepting Preflight is the only way I can get around browser CORS check when combining OpenId and JWT token auth in the same site that includes both MVC and Web Api controllers (the latter auth'd via token). Thank you! – kenswdev Apr 17 '20 at 20:16