CORS 请求错误甚至认为它已在 .Net Core 后端启用 [英] CORS request error even thought it's enabled in the .Net Core back end

查看:26
本文介绍了CORS 请求错误甚至认为它已在 .Net Core 后端启用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个测试应用程序,我想发送一个请求并获取一个令牌,但无论如何我无法获取它,因为我的后端配置中的交叉请求错误:

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();
    }

但仍然收到错误说已被 CORS 策略阻止:请求的资源上不存在Access-Control-Allow-Origin"标头

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

推荐答案

services.AddCors 放在 ConfigureServices 方法的顶部,然后以这种方式配置 cors:

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");
        }));

Configure 方法中,也在方法的顶部添加app.UseCors("MyPolicy");.这对我来说很好用,但在我尝试了很多没有的变体之前.

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.

这篇关于CORS 请求错误甚至认为它已在 .Net Core 后端启用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆