title: Enable CORS in ASP.Net Core 5 WebAPI
body: <p>There are millions of articles and questions related to this issue and yet I cannot find what's wrong with my code. I have <code>Startup</code>, <code>StartupProduction</code>, and <code>StartupDevelopment</code> as the following. Also, I am using <code>ASP.Net Core 5</code>, and based on the <a href="https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0#enable-cors-with-endpoint-routing" rel="nofollow noreferrer">documentation</a> I think I am doing this correctly.</p>
  <p>FYI, at first, I used <code>AllowAnyOrigin</code> for development but I also test <code>.WithOrigins(&quot;http://localhost:3000&quot;)</code> and it works fine. My backend runs under <code>https://localhost:44353</code> in development and under <code>https://api.example.com</code> in production.</p>
  <pre class="lang-cs prettyprint-override"><code>public class Startup
  {
      protected const string CorsPolicyName = &quot;CorsPolicyName&quot;;
  
      public virtual void ConfigureServices(IServiceCollection services)
      {
          services.AddControllers()
              .AddJsonOptions(options =&gt;
              {
                  options.JsonSerializerOptions.Converters.Add(
                      new System.Text.Json.Serialization.JsonStringEnumConverter());
              });
  
          services.AddABunchOfOtherServices();
      }
  
      public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env)
      {
          app.UseHttpsRedirection();
          app.UseStaticFiles();
          app.UseRouting();
          app.UseCors(CorsPolicyName);
          app.UseAuthentication();
          app.UseAuthorization();
  
          app.UseMiddleware&lt;CheckUserConfirmedMiddleware&gt;();
  
          app.UseEndpoints(endpoints =&gt;
          {
              endpoints.MapControllerRoute
              (
                  name: &quot;default&quot;,
                  pattern: &quot;{controller=Home}/{action=Index}/{id?}&quot;
              )
              .RequireCors(CorsPolicyName);
          });
      }
  }
  
  public class StartupProduction : Startup
  {
      public override void ConfigureServices(IServiceCollection services)
      {
          services.AddCors(options =&gt;
          {
              options.AddPolicy(
                  CorsPolicyName,
                  policy =&gt; policy
                      .WithOrigins(&quot;https://example.com&quot;, &quot;http://example.com&quot;)
                      //.WithOrigins(Configuration.GetValue&lt;string&gt;(&quot;AllowedHosts&quot;).Split(';').ToArray())
                      .AllowAnyMethod()
                      .AllowAnyHeader());
          });
  
          base.ConfigureServices(services);
      }
  
      public override void Configure(IApplicationBuilder app, IWebHostEnvironment env)
      {
          app.UseMiddleware(typeof(ErrorHandlingMiddleware));
  
          // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
          app.UseHsts();
  
          base.Configure(app, env);
      }
  }
  
  public class StartupDevelopment : Startup
  {
      public override void ConfigureServices(IServiceCollection services)
      {
          services.AddCors(options =&gt;
              options.AddPolicy(
                  CorsPolicyName,
                  policy =&gt;
                      policy
                          //.AllowAnyOrigin()
                          .WithOrigins(&quot;http://localhost:3000&quot;)
                          .AllowAnyMethod()
                          .AllowAnyHeader()
              )
          );
  
          base.ConfigureServices(services);
  
          services.AddSwaggerGen(....);
      }
  
      public override void Configure(IApplicationBuilder app, IWebHostEnvironment env)
      {
          app.UseMiddleware&lt;DevelopmentErrorHandlingMiddleware&gt;();
  
          base.Configure(app, env);
  
          app.UseSwagger();
  
          app.UseSwaggerUI(options =&gt;
          {
              options.SwaggerEndpoint(&quot;swagger/v1/swagger.json&quot;, &quot;API v1&quot;);
              options.RoutePrefix = string.Empty;
          });
      }
  }
  </code></pre>
  <p>I also tried the <a href="https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0#cors-with-default-policy-and-middleware" rel="nofollow noreferrer">default policy</a>.</p>
  <h2>Update</h2>
  <p>I have set the <code>Environment</code> to <code>Production</code> in the visual studio to debug it and now I am facing the same issue in development.</p>
  <blockquote>
  <p>Access to fetch at 'https://localhost:44353/api/v1/User' from origin 'http://localhost:3000' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.</p>
  </blockquote>
  <h1>Workaround solution</h1>
  <p>I notice that it is the IIS blocking the request. It only works when I have <code>&quot;AllowedHosts&quot;: &quot;*&quot;,</code> in my <code>appsettings.json</code>. So, as a workaround, I have added <code>&quot;MyRandomKey&quot;: &quot;https://example.com&quot;,</code> in my <code>appsettings.json</code> and use the following in my <code>Startup</code>.</p>
  <pre class="lang-cs prettyprint-override"><code>services.AddCors(options =&gt;
                  options.AddPolicy(
                      CorsPolicyName,
                      policy =&gt;
                          policy
                              .WithOrigins(Configuration.GetValue&lt;string&gt;(&quot;MyRandomKey&quot;).Split(&quot;;&quot;).ToArray())
                              .AllowAnyMethod()
                              .AllowAnyHeader()
                  )
              );
  </code></pre>