【问题标题】:CORS in ASP.NET Core in IISIIS 中 ASP.NET Core 中的 CORS
【发布时间】:2020-02-18 10:09:13
【问题描述】:

我发现了一个有趣的问题。我在 IIS 上部署了我的 ASP.NET Core REST API,当我调用它时,我遇到了这个错误:

Access to XMLHttpRequest at 'https...' from origin 'https:...' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.
Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'https:'.

但几分钟前它还在工作。我检查了响应头,它在那里:

access-control-allow-headers: content-type,odata-maxversion,odata-version
access-control-allow-methods: GET, GET,POST,PUT,DELETE,OPTIONS
access-control-allow-origin: *, *

然后我意识到我重新启动了服务。出于某种原因,每次上传服务时,我的代码和 IIS 都会重复 HTTP 响应标头值。当我在 IIS 中删除 HTTP 响应标头值时,它可以工作。这是我的 Startup.cs 代码:

public void ConfigureServices(IServiceCollection services)
    {
      services.AddCors(o => o.AddPolicy("AllPolicy", builder =>
      {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader();
      }));
      services.AddControllers();
      ...
    }

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

      app.UseHttpsRedirection();

      app.UseRouting();

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

您知道为什么每次上传服务时标题值都会重复吗?您有任何解决方法的想法吗?

【问题讨论】:

  • 如何将网站发布到 IIS?
  • @Vistari Project- 发布 - 到一个文件夹。目标运行时win-x64,部署方式:依赖框架

标签: c# .net asp.net-core cors


【解决方案1】:

尝试移动“app.UseCors("AllPolicy");”在 app.UseRouting(); 之后 所以它看起来像:

app.UseRouting();
app.UseCors("AllPolicy");

【讨论】:

    猜你喜欢
    • 2019-10-17
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 2019-06-15
    • 1970-01-01
    • 2019-08-19
    相关资源
    最近更新 更多