Home > database >  views CORS error, but you get data and it is visible C# (ASP .Net Core)
views CORS error, but you get data and it is visible C# (ASP .Net Core)

Time:01-06

I have this configuration in my Startup method, apparently everything works fine

services.AddCors(options =>
        {
            options.AddPolicy("MyPolicy",
                builder => builder.WithOrigins("https://localhost:5000",  
                                               "http://localhost:3000",
                                               "http://localhost:3001")
                                  .AllowAnyHeader()
                                  .WithMethods("PUT", "GET"));
        });


app.UseHttpsRedirection();

app.UseCors("MyPolicy");
app.UseRouting();

app.UseAuthorization();

But when I start to do tests with another url that is not registered, the request shows a cors error but at the same time the response is shown, so does it mean that I run my services without being registered?

In this screenshot, you can see the url to which I make a request

image here

What is the right thing to do to secure my API? I have also read that browsers will always execute requests even if it is not visible

CORS error, but data is fetched regardless

Thank you very much for reading me, I'm new to this

CodePudding user response:

the dot.net code in Configure and ConfigureService is correct. try allow any method and remove with origins. see if you can hit the endpoint with postman

 options.AddPolicy("EnableCORS", builder =>
                {
                    builder.AllowAnyOrigin()
                       .AllowAnyHeader()
                       .AllowAnyMethod();
                });

CodePudding user response:

Firdtly,the url is http://localhost:44344,so you need to add it into WithOrigins.And you need to make sure the method type of the request is including in WithMethods("PUT", "GET").Also,you'd better put app.UseCors("MyPolicy"); between app.UseRouting(); and app.UseAuthorization();.

services.AddCors(options =>
        {
            options.AddPolicy("MyPolicy",
                builder => builder.WithOrigins("https://localhost:5000",  
                                               "http://localhost:3000",
                                               "http://localhost:3001",
                                               "http://localhost:44344")
                                  .AllowAnyHeader()
                                  .WithMethods("PUT", "GET"));
        });


app.UseHttpsRedirection();


app.UseRouting();

app.UseCors("MyPolicy");

app.UseAuthorization();
  •  Tags:  
  • Related