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

查看:45
本文介绍了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 放在 ConfigureSevices 方法的顶部,然后以这种方式配置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天全站免登陆