.NET core OPTIONS requests return 405 errors
Asked Answered
E

1

6

I need to add CORS support to a .NET core 3.1 API (was 2.2, but I decided to update at the same time). I thought this was going to be easy. The documentation here: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1 looks quite simple. I want to support the same CORS policy across all endpoints. So, I thought I could leave my controllers alone and just make the changes to startup.cs. What am I missing?

I have a POST endpoint, but the OPTIONS requests returns a 405 error. I thought the CORS middleware was supposed to handle the request, so that I don't have to think about CORS at all inside the controllers.

Startup.cs

  namespace MyAPI
  {
    public class Startup
    {

        readonly String ALLOW_ALL = "AllowAll";
        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.Configure<IISOptions>(options =>
            // {
            //     options.AutomaticAuthentication = true;
            // });
            services.AddLogging();
            services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                {
                    builder
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                    // .AllowCredentials();
                });
            });
            services.AddMvc(MvcOptions => MvcOptions.EnableEndpointRouting = false);

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseRouting();

            // if (env.IsDevelopment())
            // {
            // app.UseDeveloperExceptionPage();
            app.UseCors();
            // }

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

            app.UseMvc();
        }
    }
}

MyController.cs

namespace MyProj.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FacilitiesController : ControllerBase
    {

        public FacilitiesController()
        {
        }


        [HttpPost]
        public JsonResult FloorPlanURL([FromBody] UniqueFloor theFloor)
        {
          <stuff happens>
          return new JsonResult(new {success = true, url = out});
        }

I've been through several iterations, looking here as well: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#enable-cors-with-endpoint-routing. I'm probably missing something small and simple. I could add manual OPTIONS handlers in all the controllers, but that seems like a pretty lousy solution.

Endosmosis answered 15/1, 2020 at 23:10 Comment(3)
Hello. I am experiencing the exact same thing. Did you ever solve this?Aenea
Make sure your OPTIONS request has both Access-Control-Request-Method and Origin headers or middleware will reject with 405.Residence
Hello. I am experiencing the exact same thing. Did you ever solve this?Permenter
Y
6

you need to modify your class StartUp.cs, try to put the code like this...

public void ConfigureServices (IServiceCollection services) {
    services.AddLogging ();
    services.AddCors (); // just adding the cors to the services
    services.AddMvc ().SetCompatibilityVersion (CompatibilityVersion.Version_2_2);
}
public void Configure (IApplicationBuilder app, IHostingEnvironment env) {
    // global cors policy
    app.UseCors (x => x
        .AllowAnyOrigin ()
        .AllowAnyMethod ()
        .AllowAnyHeader ()); // configure CORS

    app.UseHttpsRedirection ();
    app.UseMvc ();
}

And CORS must works correctly for all your Apicontrollers.

If the error code 405 continues to appear: Means you are not calling correctly the endpoint.

Please, verify and give me a feedback about the result.

Yellowlegs answered 15/3, 2020 at 3:52 Comment(1)
this works for me, thanksAristotle

© 2022 - 2024 — McMap. All rights reserved.