0

While testing my dot net core web api with ajax call, chrome replaces my get with Option in the request header when i monitor with fiddler. I followed the code here Enable OPTIONS header for CORS on .NET Core Web API and still not working. How do I achieve this? Here is my start up file

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;
    });

    services.AddCors(options => options.AddPolicy("AllowCors", p => 
        p.AllowAnyOrigin().AllowAnyMethod().AllowCredentials().AllowAnyHeader()));

    services.Configure<IISOptions>(options =>
    {
        options.ForwardClientCertificate = false;
    });

    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseOptions();
    app.UseCors("AllowCors");
    app.UseDefaultFiles();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseHttpsRedirection();

    app.UseMvc(routes =>
    {
        routes.MapRoute(name: "default", template: "{controller=Account}/{action=Login}/{id?}");
    });
}
ekad
  • 14,436
  • 26
  • 44
  • 46
Mcbaloo
  • 157
  • 5
  • 18
  • Did you add the middleware class explained in the solution? – Dr. Roggia Nov 26 '18 at 11:18
  • Have you added the `AllowCors` policy to the relevant controllers? – Martin Costello Nov 26 '18 at 11:21
  • I added the middleware class and also included it in my startup.cs\ – Mcbaloo Nov 26 '18 at 11:26
  • i added AllowCors on the relevant controller too – Mcbaloo Nov 26 '18 at 11:26
  • 1
    What do you mean by 'not working'? What error did you get? Also are you hosting this in IIS? – Rosdi Kasim Nov 26 '18 at 11:59
  • You don't need `UseOptions` (it's handled by `UseCors`) and you don't need to set attributes on your controllers when you have `UseCors` with a policy name (like in your example). – Kirk Larkin Nov 26 '18 at 12:00
  • This is what i got from developer tool from origin 'https://localhost:44338' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. . I checked Fiddler and noticed Options is added – Mcbaloo Nov 26 '18 at 12:01
  • You may see this if you have an error in your application. Because then your OPTIONS logic may not be reached and the error response won’t include the header allowing OPTIONS calls so you get another error than the actual one. I can just recommend that you troubleshoot this with debugging (F5) and see if your code is even hit. (Or use logging if you cannot debug for some reason) – Niels Brinch Nov 26 '18 at 15:12

2 Answers2

2

This should enable OPTION header

          app.UseCors(builder => builder.WithOrigins("http://example.com")
          .AllowAnyHeader()
          .AllowAnyMethod()
          .AllowCredentials());

fit it to your needs if you do not want to enable any header / method or credentials.

1

If you are hosting on IIS, one possible reason is you are getting this is because IIS is blocking OPTIONS verb.

One telltale indication is you are getting 404 error during OPTIONS request.

To fix this, you need to explicitly tell IIS not to block OPTIONS request.

Go to Request Filtering:

IIS Request Filtering

Make sure OPTIONS is allowed:

Make sure OPTIONS is True

Or, just create a web.config with the following setting:

<system.webServer>
    <security>
        <requestFiltering>
            <verbs>
                <remove verb="OPTIONS" />
                <add verb="OPTIONS" allowed="true" />
            </verbs>
        </requestFiltering>
    </security>
</system.webServer>
Rosdi Kasim
  • 24,267
  • 23
  • 130
  • 154
  • at the moment, the API is not published on IIS. Everything is still in visual studio ...can i add the config file before now that i'm still testing locally without publishing? – Mcbaloo Nov 26 '18 at 12:58
  • @Mcbaloo That does not make sense, you should not need to set CORS on localhost. – Rosdi Kasim Nov 26 '18 at 13:18
  • How then do i test the Api with my web application without deploying it on IIS. The Api and web application are together – Mcbaloo Nov 26 '18 at 13:28