【问题标题】:CORS issue after upgrading to DotNet 3.1 while connecting from localhost to server API从 localhost 连接到服务器 API 时升级到 DotNet 3.1 后出现 CORS 问题
【发布时间】:2020-10-20 13:22:25
【问题描述】:

当我尝试从本地系统 - localhost:4200 连接到托管在 IIS 上的 API (DotNet Core 3.1) 时,在浏览器中将项目迁移到 DotNet Core 3.1 后出现以下错误

CORS 策略已阻止从源“http://localhost:4200”访问“https://dev.ncop.firstam.net/multisiteservice/api/v1/test/method”处的 XMLHttpRequest:响应预检请求未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

这是我的 startup.cs 中的 CORS 代码 sn-p

    public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                var allowedOrigin = Configuration["AppSettings:CorsAllowedOrigin"];
                {
                    options.AddPolicy("SiteCorsPolicy",
                    builder => builder.AllowAnyOrigin()
                    .WithOrigins(allowedOrigin)
                    .AllowAnyMethod()
                    .AllowCredentials()
                    .AllowAnyHeader());
                }
            });
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
            {
app.UseCors("SiteCorsPolicy");
            app.UseAuthentication();
            app.UseMvc();
            //Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();
    }

这是我的 AppsettingsFile:

 "AppSettings": {
    "CorsAllowedOrigin": "http://localhost:4200/,https://dev.ncop.fistam.com/,https://staging.ncop.fistam.com/,https://ncop.fistam.com,http://azuvnintfint551.fastts.firstam.net,https://staging.webservices.firstam.net
  }

如何从本地系统连接到服务器 API?我错过了什么。 尝试连接 API 的 UI 应用程序是基于 Angular 5 构建的

【问题讨论】:

    标签: .net-core cors .net-core-3.1


    【解决方案1】:

    根据docs

    网址不得包含尾部斜杠 (/)。如果 URL 终止 带/,比较返回false,不返回header。

    AppSettings 中的域不应包含尾部正斜杠 (/)。

    你能用这个试试吗:

     "AppSettings": {
        "CorsAllowedOrigin": "http://localhost:4200,https://dev.ncop.fistam.com,https://staging.ncop.fistam.com,https://ncop.fistam.com,http://azuvnintfint551.fastts.firstam.net,https://staging.webservices.firstam.net
      }
    

    【讨论】:

      猜你喜欢
      • 2019-06-14
      • 2012-10-25
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      • 2020-05-25
      • 2018-10-07
      • 1970-01-01
      • 2022-12-07
      相关资源
      最近更新 更多