0

I have CORS working fine in "normal" {controller}/{action}/{id?} controllers. However CORS does not work in action methods with specific [Route("routname")] attributes.

Sample controller with route:

[Route("api/[controller]")]
[ApiController]
public class CustomerController : ControllerBase
{

[HttpPost]
public async Task<ActionResult<Guid>> Post([FromBody] Customer value)
{
...
}

[HttpPost]
[Route("payment")]
public async Task<ActionResult<CustomerPaymentResponse>> Pay([FromBody] CustomerPaymentRequest value)
{ 
...
}

My ConfigureServices method in startup.cs file looks like this:

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

            services.AddRouting();           

            services.AddControllers();
        }

and Configure method looks like this:

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();

            app.UseCors();

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

            app.UseHttpsRedirection();
            app.UseAuthentication();
            app.UseAuthorization();

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

If I POST to /api/customer CORS is working.

If I POST to /api/customer/payment CORS does not work (Chrome says: "... 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 have followed the provided answer for Can't enable CORS for specific API controllers in ASP.NET Core WebApp targeting netcoreapp3.0 but issue still remains for me.

Any thoughts?

Federico
  • 11
  • 1

2 Answers2

0

Itβ€˜s your RouteAttribute: With Asp.Net-Framework this could work:

[HttpPost]
[Route("payment")]

public async Task<ActionResult<CustomerPaymentResponse>> Pay([FromBody] CustomerPaymentRequest value)
    { 
    ...
    }

But with Core you need, because with Route, the RouteAttribute of the Controller is overridden:

[HttpPost ("payment")]
public async Task<ActionResult<CustomerPaymentResponse>> Pay([FromBody] CustomerPaymentRequest value)
{ 
...
}
Nikolaus
  • 1,859
  • 1
  • 10
  • 16
0

Answering my own question. I found this post: Trouble with CORS Policy and .NET Core 3.1

I had an error inside my Pay method.

As that post says, Sometimes "Non-CORS" .NET Server-side Errors Can Be Returned as CORS Errors

Federico
  • 11
  • 1