Access to XMLHttpRequest has been blocked by CORS policy in ASP.NET CORE
Asked Answered
M

1

6

I tried to make connection from my side client to the API Server with ajax, but I get a error in the response : Access to XMLHttpRequest at 'https://localhost:44381/api/webinars' from origin 'http://localhost:5003' 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 tried to edit the CROS policy in the API but I still have the same error. This is my ajax code from MVC:

 $.ajax({
            url: "https://localhost:44381/api/webinars",
            type: 'POST',
            headers: {
                contentType: "application/json",
            },
            body: JSON.stringify(body),
            success: function (data) {
                console.log(data);
            },
            failure: function (err) {
                console.log(err);
            }

        });

StartUp from API:

  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.AddCors(options =>
        {
            options.AddPolicy("AllowMyOrigin",
            builder => builder.WithOrigins(
                "http://localhost:5003/",
                "http://apirequest.io")
                .WithMethods("POST","GET","PUT")
                .WithHeaders("*")
                );
        });
          //code
    }

   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //code
        app.UseCors("AllowMyOrigin");
        app.UseHttpsRedirection();
        app.UseMvc();
    }
}

Controller in the API:

[EnableCors("AllowMyOrigin")]

[Route("api/[controller]")]
[ApiController]
public class WebinarsController : ControllerBase
{
        // POST: api/Webinars
    [HttpPost]
    public async Task <ActionResult> PostAsync([FromBody] Item newItem)
    {     
         //code
      }
 }

Thanks for the answer.

Marshamarshal answered 4/11, 2019 at 20:56 Comment(2)
#53298978Gurrola
You should remove the path suffix after your url: http://localhost:5003/ -> http://localhost:5003Muncy
C
1

you should replace app.UseMvc(); with

app.UseEndpoints(endpoints =>
{
   endpoints.MapControllers();
});
Creamery answered 28/4, 2020 at 21:44 Comment(2)
also no need to use [EnableCors("AllowMyOrigin")] it already configured in startupCreamery
Your comment would probably be better as an edit to your answer. Thanks!Ciaracibber

© 2022 - 2024 — McMap. All rights reserved.