Hooman Limouee
Hooman Limouee

Reputation: 1403

Response to preflight request doesn't pass access control (Angular 2 - Web Api)

I've several projects that one of them is for Authentication. However I've set CORS configuration, it still returns errors.

Note: Web Api apps work with postman.

Here is what I've done so far:

Startup.cs

[assembly: OwinStartup(typeof(LabelGenerator.Startup))]
namespace LabelGenerator {
    public partial class Startup {
        public void Configuration(IAppBuilder app) {
            ConfigOAuth(app);
            ConfigWebApi(app);
        }
    }
}

Startup.Auth.cs

namespace LabelGenerator {
    public partial class Startup {
        private void ConfigOAuth(IAppBuilder app) {
            OAuthBearerAuthenticationOptions oAuthServerOptions = new OAuthBearerAuthenticationOptions();
            // Token Generation
            app.UseOAuthBearerAuthentication(oAuthServerOptions);
        }

        private void ConfigWebApi(IAppBuilder app) {
            HttpConfiguration conf = new HttpConfiguration();
            WebApiConfig.Register(conf);
            app.UseWebApi(conf);

            // CORS
            app.UseCors(CorsOptions.AllowAll);
        }
    }
}

Web.config

<modules runAllManagedModulesForAllRequests="true">
  <remove name="ApplicationInsightsWebTracking" />
  <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>

Upvotes: 0

Views: 695

Answers (1)

Hooman Limouee
Hooman Limouee

Reputation: 1403

According to this answer I changed this :

private void ConfigWebApi(IAppBuilder app) {
    HttpConfiguration conf = new HttpConfiguration();
    WebApiConfig.Register(conf);
    app.UseWebApi(conf);

    // CORS
    app.UseCors(CorsOptions.AllowAll);
}

to this :

private void ConfigWebApi(IAppBuilder app) {
    HttpConfiguration conf = new HttpConfiguration();
    WebApiConfig.Register(conf);

    // CORS
    app.UseCors(CorsOptions.AllowAll);
    app.UseWebApi(conf);
}

And now CORS is working properly.

Upvotes: 1

Related Questions