.net core api CORS Get works but cors gets 405

asp net core no 'access-control-allow-origin' header is present on the requested resource
setisoriginallowedtoallowwildcardsubdomains
asp.net core 405 method not allowed
asp.net core 3.0 cors
asp net core cors options 404
signalr core cors not working
asp.net cors not working
contains cors metadata, but a middleware was not found that supports cors

I have the following middleware:

    namespace TimeManagement
{
    public class CorsMiddleware
    {
        private readonly RequestDelegate _next;

        public CorsMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public Task Invoke(HttpContext httpContext)
        {
            httpContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            httpContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
            httpContext.Response.Headers.Add("Access-Control-Allow-Headers",
                "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name");
            httpContext.Response.Headers.Add("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");
            return _next(httpContext);
        }
    }

// Extension method used to add the middleware to the HTTP request pipeline.
    public static class CorsMiddlewareExtensions
    {
        public static IApplicationBuilder UseCorsMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CorsMiddleware>();
        }
    }
}

And the following startup class:

namespace TimeManagement
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<WorkTimeContext>(opt =>
                opt.UseInMemoryDatabase("WorkTime"));
            services.AddDbContext<TimeManagementContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("TimeManagementContext")));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();
            app.UseCorsMiddleware();
            app.UseRouting();
            app.UseAuthorization();

            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }
    }
}

Then I attempt to run https://localhost:5001/api/WorkTimes GET and it returns without issues.

Now I am using an Angular frontend and from there I am trying to post. As you may know, it sends an OPTIONS first and here I get a CORS error:

You need to send status code 200 for CORS preflight request, which your middleware is not setting right now.

Why don't you just use the ASP.NET CORS middleware which handles this? ASP.NET CORS Middleware

OPTIONS request being handled and returns 405 � Issue #453 , Why is the versioning getting in the way of an OPTIONS request? commonsensesoftware added question asp.net core labels on Jan 29, 2019 exactly why your CORS configuration isn't working, but it's not related to API� By Rick Anderson and Kirk Larkin. This article shows how to enable CORS in an ASP.NET Core app. Browser security prevents a web page from making requests to a different domain than the one that served the web page.

Can you try putting the following in web.config:

<httpHandlers>
  ... 
    <add path="*" verb="OPTIONS" type="System.Web.DefaultHttpHandler" validate="true"/>
</httpHandlers>

CORS does not work with pre-flight request � Issue #18665 � dotnet , Diagnostics[1] Request starting HTTP/2 OPTIONS https://localhost:5001/api/tags/ Executing endpoint '405 HTTP Method Not Supported' info: Microsoft. mkArtakMSFT added area-mvc feature-cors labels on Jan 29 NET Core framework, which hasn't been addressed yet, please file a new issue. Recently, I’ve been working on an Angular app, powered with a .NET Core API. Everything was working well and smoothly when running both on my local machine. After pushing code to the beta server, most of it was working fine. The front-end was being able to call GET, POST and OPTIONS requests normally.

chrome doesn't support this.

​Access to XMLHttpRequest at '...' from origin '...' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Solution 1 [Temporary Development Solution]

chrome://flags/#out-of-blink-cors 

Disable the out-of-blink-cors flag by copying and pasting that address into the address bar of Chrome followed by [enter]. In the page that opens you'll see a highlighted so-called 'flag' (experiment). Disable it and restart Chrome (Edit: previously I said to enable the flag but only disabling seems to work)

In many cases that solves the issue. You can upvote this feature on chrome here

Solution 2 (Recommended)

Create your api under in the sub-domain

your api url will be http://localhost:4200/api/YourEndpoint

Here Voyage is our angular application. Under it Api where we host our API so which will be under a same domain so CORS policy is not violated.

ASP.NET Core and CORS Gotchas, Check that it works. When it's all said and done you now should get the appropriate CORS headers with your response: http. HTTP� Despite the rather easy workaround, such an issue is definitely a though one, as it will easily affect most ASP.NET Core Web API and Web Applications when they get deployed on a live environment: that’s because the WebDAV module, although not supported by IIS Express, happens to be enabled in most production servers.

Cors errors can be very trick. Sometimes the browser returns this erros without really call your api. So first step you need to be sure that the browser call your API. To do this I usually add a dumb inline middleware and put a breakpoint in it. You could add a logger to it too.

The dumb middleware sample:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Use(async (context, next) =>
    {
        await next.Invoke();
        // Do logging or other work that doesn't write to the Response.
    });

    // The others middlewares.
}

Now that you know if the problem is in your browser or in your app you can what can you do?

1) If the problem is in your browser, follow the instruction from @Eldho answer to enable it.

2) If the problem is in your app please read the rest of my answer.

Middlewares are executed in the same sequence you call it in Configure method.

Maybe HttpsRedirection is returning this error. (Big maybe here)

You can try declare your custom app.UseCorsMiddleware() before HttpsRedirection. But I suggest you to use Asp.net Cors Middlewares that already exists and works fine. Why reinvent the wheel?

This is a sample of Asp.Net Core v2.1 Cors Middleware

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("Any", 
            builder => 
            {
                builder
                    .AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
            });
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors("Any");
    // The others middlewares.
}

Another approach (only for development) is to use SPA Middleware to forward the requests your SPA. This way your angular app and your Asp.Net app will answer on the same port of localhost and chrome will not block any. But it just work as temporary solution. It is not recommended to use this in production.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors("Any");

    // The others middlewares.

    if (env.IsDevelopment())
    {
        app.UseSpa(spa =>
        {
            spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
        });
    }
}

Cross-Origin Resource Sharing (CORS), For example, XMLHttpRequest and the Fetch API follow the same-origin policy. Modern browsers use CORS in APIs such as XMLHttpRequest or Fetch But the CORS standard means servers have to handle new request and The Cross- Origin Resource Sharing standard works by adding new HTTP� API versioning gets in the way of every request that makes it a controller action. It versions all APIs, not just specific HTTP methods such as GET, PUT, POST, DELETE, or PATCH. It's perfectly reasonable to have an API that maps to OPTIONS. I have used this myself as way to query the server as to which API versions and other features are available.

How to Enable CORS in ASP.NET Core By Example, NET Core, what is the Same Origin Policy and how CORS works. NET Core API using only the latest and greatest technologies. The browser shall receive the response data, but this data shall not be accessible to the� Last night I was working on updating my ASP.NET Core AlbumViewer sample application to Angular 2.0 and in the process ran into CORS problems. Angular 2.0's default working environment runs a development server off a seperate port which is effectively a seperate domain and all calls back to the main ASP.NET site for the API calls effectively are cross domain calls.

Enable Cross-Origin Requests (CORS) in ASP.NET Core, Learn how CORS as a standard for allowing or rejecting cross-origin requests in an How CORS works; CORS in IIS; Test CORS; Additional resources The call to UseCors must be placed after UseRouting , but before UseAuthorization . MyDisplayRouteInfo(); // GET api/values/5 [HttpGet("{id}")] public� Now let’s run it with dotnet run and see what we’re working with: CORS. CORS being ‘disabled’ by default is the safe thing to do, you don’t necessarily want any other website to be able to access your API on a user’s behalf, some nefarious deeds could potentially occur. You can read more about the background of CORS here. All that

[Solved] CORS issue when angular and web API(.NET core) is used , But, when I enable Anonymous Authentication I started getting 500 Internal Server services) method. and everything works like a charm. I have a .net core WebAPI in 3.1 hosted on IIS with Windows Authentication. While making a Fetch call to the API, it gets CORS issue for the pre-flight request. CORS pre-flight works when setting both Anonymous and Windows Authentication together and the following setting in the Startup.cs file.

CORS — IdentityServer4 1.0.0 documentation, Many endpoints in IdentityServer will be accessed via Ajax calls from JavaScript- based clients. One approach to configuring CORS is to use the AllowedCorsOrigins collection In general, both should work together in the same application. NET Core CORS services and IdentityServer is if you decide to create a custom� At this time my controller works as expected because I found the reason for this issue after a while and corrected the code. I may be able to get some spare time in 2-3 weeks to create a sample project.

Comments
  • Note that you cannot use * as the Origins header if you also accept authentication. If you use auth, the Origins header needs to be fully specified, not a wildcard. See MDN, scroll down to "Credentialed Requests and Wildcards". I do not think this is the cause of your issue, but it will affect you at some point.
  • How do you deploy your api? Have you considered using build-in cors middleware docs.microsoft.com/en-us/aspnet/core/security/cors?
  • @Gaurvasa i dont have a web.config file ?