3

I am facing this issue:

Access to XMLHttpRequest at 'http://localhost:5000/api/surpactemp/' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

On backend side I tried this way and didn't worked:

.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()

I've been trying several ways to solve using Microsoft reference (below), but, no success so far. Also, I already tried not pass the headers object on Angular, then, I receive the error:

No 'Access-Control-Allow-Origin' header is present on the requested

Environment:

  • Dotnet Core 3.1
  • Angular 8

Backend: Startup.cs

//ConfigureServices
services.AddCors(options =>
{
    options.AddPolicy(name: "CorsPolicy",
        builder => builder.WithOrigins("http://localhost:4200")
                          .WithHeaders(HeaderNames.ContentType, "application/json")
                          .WithMethods("PUT", "DELETE", "GET", "OPTIONS", "POST")        
        );
});

//Configure
 app.UseHttpsRedirection();

 app.UseRouting();

 app.UseCors("CorsPolicy");

 app.UseAuthorization();

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

Frontend: form-service.ts

httpOptions = {
    headers: new HttpHeaders({
      // 'Content-Type': 'application/json',
      // 'withCredentials': 'false',
      // 'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json'
    })
};

return this.httpClient.post('http://localhost:5000/api/surpactemp/', JSON.stringify(data.path), this.httpOptions);

Reference: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#preflight-requests

3
  • 1
    Where's your call to UseCors? It's position within the middleware pipeline setup is important. Apr 17, 2020 at 20:09
  • @KirkLarkin On Backend section, app.UseCors("CorsPolicy")
    – wbail
    Apr 17, 2020 at 20:18
  • 1
    Yeah, I know. I mean where is it within Startup.Configure? Which other calls is it between? Middleware order is important, so it's possible you've got the order wrong. Apr 17, 2020 at 20:58

5 Answers 5

14

I discovered the issue, the app.UseHttpsRedirection() method requires https clients.

On Startup.cs at Configure method:

//app.UseHttpsRedirection(); <-- Commented this line

app.UseRouting();

app.UseCors();

app.UseAuthorization();

2
  • Thanks, saved me some time, I was also querying an http endpoint
    – Ferenc
    Oct 21, 2020 at 20:32
  • Thanks. Helped me too.
    – duyn9uyen
    Dec 22, 2020 at 15:25
2

This solution solved my case:

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.AddControllers();
            services.AddCors();
        }

        // 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.UseRouting();

            app.UseCors(
                options => options.SetIsOriginAllowed(x => _ = true).AllowAnyMethod().AllowAnyHeader().AllowCredentials()
            );

            app.UseAuthorization();

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

from https://github.com/dotnet/aspnetcore/issues/16672

0
services.AddCors(); // Make sure you call this previous to AddMvc
services.AddMvc();       

 app.UseCors(
     options => options.WithOrigins("http://localhost:4200","https://localhost:4200")
                .AllowAnyHeader().AllowAnyMethod().AllowCredentials()
             );

Edited:

   public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(
         options => options.WithOrigins("http://localhost:4200", "https://localhost:4200").AllowAnyHeader().AllowAnyMethod().AllowCredentials());




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


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

        }     
1
  • Same, didn't work... Access to XMLHttpRequest at 'localhost:5000/api/surpactemp' from origin 'localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
    – wbail
    Apr 20, 2020 at 18:48
0

Looks like it's this that is the problem (went away as soon as I realized the redirection is being done in my service with app.UseHttpsRedirection(); and the javascript calls were to the "http", instead of "https". I wish the error was more specific, but this fixed it!

-2

You can use proxy configuration.

look this https://www.youtube.com/watch?v=D9oFe6rHjpY

1
  • Hi, I already tried by this way using proxy on Angular, and didn't worked as well...
    – wbail
    Apr 17, 2020 at 20:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.