title: Asp.Net Core WebAPI CORS Not working
body: <p>I am trying to implement the WebAPI Service by using .Net Core and I couldn't manage to set up the CORS working correctly.</p>
  
  <p>I got the main application 'MainApp' and it's going to generate the Invoice on the fly and I want to promote it as the service.  This is not a pure WebAPI application.  I just want to add this InvoiceController as the WebAPI and there are other Controllers such as HomeController, ProductsController, etc... with views and cshtml.</p>
  
  <p>I got separate Classic WebForm .Net Application which is going to call that InvoiceGeneration Service via Ajax and display values on the website.</p>
  
  <p>When I run my ajax script, I got this famous CORS error.</p>
  
  <p><a href="https://i.stack.imgur.com/SdBa3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SdBa3.png" alt="enter image description here"></a></p>
  
  <p>This is my ajax Get method.  It doesn't matter whether I put <code>xhrFields</code> or not.  I even changed <code>dataType: 'jsonp'</code> and it still gives me the same error.</p>
  
  <pre><code>$.ajax({
                  type: "GET",
                  url: 'http://localhost:57012/invoice/test/123',
                  dataType: 'json',                
                  contentType: 'application/json',
                  success: function (data) {                    
                      console.log(data);
                  },
                  xhrFields: {
                      withCredentials: true
                  }
              });
  </code></pre>
  
  <p><strong>InvoiceController.cs</strong></p>
  
  <p>My Invoice Service is very simple... Just one method which is returning some JSON values.</p>
  
  <p>Since I am using Policy and Claims to determine the security, I put <code>AllowAnonymous</code> attribute.  Even though I remove that restriction, it still doesn't work.</p>
  
  <pre><code>public class InvoiceController : Controller
      {        
          [HttpGet]
          [AllowAnonymous]        
          [EnableCors("AllowAll")]
          public async Task&lt;IActionResult&gt; Test(string id)
          {
  
              return new JsonResult(id);
          }
      }
  </code></pre>
  
  <p><strong>Startup.cs</strong></p>
  
  <p>I added AllowAll Policy to allow all type of requests.</p>
  
  <pre><code>    public void ConfigureServices(IServiceCollection services)
              {
                  services.AddDbContext&lt;DbContexts.PJDbContext&gt;(options =&gt; options.UseSqlServer(Configuration.GetConnectionString("PJConnection")));
  
                  services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;();
  
                  services.AddMvc()
                      .AddJsonOptions(o =&gt; o.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)
                      .AddJsonOptions(o =&gt; o.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver());
  
                  services.AddCors(options =&gt; options.AddPolicy("AllowAll", p =&gt; p.AllowAnyOrigin()
                                                                  .AllowAnyMethod()
                                                                   .AllowAnyHeader()
                                                                   .AllowCredentials()));    
  
  
                  services.AddAuthorization(options =&gt;
                  {
                      options.AddPolicy(Constants.CONST_POLICY_SUPERADMIN, policy =&gt; policy.RequireRole(Constants.CONST_ROLE_SUPERADMIN));
                      options.AddPolicy(Constants.CONST_POLICY_STUDENT, policy =&gt; policy.RequireRole(Constants.CONST_ROLE_STUDENT, Constants.CONST_ROLE_ADMIN, Constants.CONST_ROLE_SUPERADMIN));
                  });
              }
  
  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions&lt;AppSettings&gt; AppSettings)
              {
                  loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                  loggerFactory.AddDebug();
  
                  if (env.IsDevelopment())
                  {
                      app.UseDeveloperExceptionPage();
                  }
                  else
                  {
                      app.UseExceptionHandler("/Home/Error");
                  }
  
                  app.UseStaticFiles();
  
                  if (env.IsProduction())
                  {
                      app.UseStaticFiles(new StaticFileOptions()
                      {
                          FileProvider = new PhysicalFileProvider(AppSettings.Value.FilePathToUpload),
                          RequestPath = new PathString("/Files"),
                      });
                  }
  
                  app.UseCookieAuthentication(new CookieAuthenticationOptions
                  {
                      AuthenticationScheme = "Cookie",
                      LoginPath = new PathString("/Account/Login/"),
                      AccessDeniedPath = new PathString("/Account/Forbidden/"),
                      AutomaticAuthenticate = true,
                      AutomaticChallenge = true
                  });
  
                  app.UseCors("AllowAll");
                  app.UseMvc(routes =&gt;
                  {
                      routes.MapRoute(
                          name: "default",
                          template: "{controller=Home}/{action=Index}/{id?}");
                  });
              }
  </code></pre>
  
  <p><strong>Here is the interesting part.</strong>  </p>
  
  <p>I created another new .Net Core WebAPI project and copy this CORS Setup to the Startup.cs and InvoiceController to the new project.  CORS is working fine and my AJAX can call that method from the new project.  </p>
  
  <p>But I don't want to make multiple projects and can't I embed that WebAPI in the existing MVC WebApp Project?</p>
  
  <p>I have seen some tutorials which is running both WebAPIs and MVC Controllers side by side in the same project  (obviously they are in the same domain.  So, CORS is not a problem for them).  Very confusing.</p>
  
  <p>Could you guys please help me with it?</p>
  
  <p>PS. This <a href="https://www.html5rocks.com/en/tutorials/cors/" rel="nofollow noreferrer">Html5Rocks</a> tutorial js script doesn't work too.</p>
  
  <p>In my opinion, I don't think there is nothing wrong with JqueryAJAX script.
  I got another pure WebAPI .Net Core service and I managed to set up the CORS correctly with the same 'AllowAll Policy' code.  I can call that service from any cross domain websites by using this simple Jquery script. </p>
  
  <pre><code>$.ajax({
                  type: "GET",
                  url: 'http://oakapi/staff/byid/2618',
                  dataType: 'json',                
                  contentType: 'application/json',
                  success: function (data) {
                      console.log(data);
                  }             
              });
  </code></pre>