CORS request error even thought it's enabled in the .Net Core back end

為{幸葍}努か 提交于 2021-01-29 15:50:27

问题


I have a test app, which I want to send a request and get a token, but anyway I can't get it due to the cross request error in my back end in the configuration I have:

  public void ConfigureServices(IServiceCollection services)
    {


        services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader()
                   .AllowCredentials().WithOrigins("http://localhost:4200");
        }));

and added the following on the Configure part:

  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {


        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }
        app.UseAuthentication();

            app.UseCors("MyPolicy");

        app.UseMvc();
    }

but still getting the error saying has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource


回答1:


Put services.AddCors in the top of your ConfigureSevices method, then configure cors that way:

services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
        {
             builder.AllowCredentials()
    .AllowAnyMethod()
    .AllowAnyHeader()
    .WithOrigins("http://localhost:4200", "https://localhost:4200");
        }));

In Configure method add app.UseCors("MyPolicy"); at the top of method too. That works fine for me, but before i tried a lot of variants which did not.



来源:https://stackoverflow.com/questions/61443057/cors-request-error-even-thought-its-enabled-in-the-net-core-back-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!