【问题标题】:CORS Error in Core and React when hosting in IIS在 IIS 中托管时 Core 和 React 出现 CORS 错误
【发布时间】:2022-10-15 20:29:13
【问题描述】:

在 React + ASP.net Core 上工作,在本地主机上工作正常,当我托管在 IIS 服务器上时,我收到 CORS 错误。

“CORS 策略已阻止从源 'http://10.100.221.6:9039' 在 'http://10.100.221.6:9037/authentication' 处获取的访问权限:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。”

这里http://10.100.221.6:9037/authentication 是托管在端口 9037 中的我的 ASP.net Core 应用程序

http://10.100.221.6:9039 是我在端口 9039 中的反应应用程序

以下事情已经尝试过

  1. 启动设置我在 ASP.net Core 中添加了 URL “ReactWindowsAuth”:{ "commandName": "项目", “启动浏览器”:是的, "launchUrl": "天气预报", “环境变量”: { "ASPNETCORE_ENVIRONMENT": "发展" }, "applicationUrl": "https://localhost:5001;http://localhost:5000;http://10.100.221.6:9039" }, “码头工人”:{ "commandName": "Docker", “启动浏览器”:是的, "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/weatherforecast", “publishAllPorts”:是的, “使用SSL”:真 } } }

  2. 在 appsetting 中,包含 CORS "AllowedHosts": "*", “CorsOrigins”:[“http://localhost:3000”,“http://10.100.221.6:9039”],

  3. 在反应应用程序中,Authentication-api 添加了 api

     const apiBase = "http://10.100.221.6:9037/authentication";
    
     class AuthenticationService {
     getRoles() {
     let request = Object.assign({}, requestBase, { method: "GET" });
     let url = `${apiBase}`;
     return fetch(url, request).then(handleResponse);
     }
     }
    

【问题讨论】:

    标签: reactjs asp.net-core


    【解决方案1】:

    您可以在 ASP.NET Core 端启用 CORS。

    var  MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
    
    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.AddCors(options =>
    {
        options.AddPolicy(name: MyAllowSpecificOrigins,
                          builder =>
                          {
                              builder.WithOrigins("http://example.com",
                                                  "http://www.contoso.com");
                          });
    });
    
    // services.AddResponseCaching();
    
    builder.Services.AddControllers();
    
    var app = builder.Build();
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    
    app.UseCors(MyAllowSpecificOrigins);
    
    app.UseAuthorization();
    
    app.MapControllers();
    
    app.Run();
    

    你可以参考Microsoft document

    【讨论】:

    • 谢谢,我已经将上面的代码添加到我的 asp.net Core Startup 中,仍然是同样的错误:(
    • 您使用的是哪个版本的 ASP.NET 核心?
    • ASP.net 核心 3.1
    • 等等,让我更新 asp.net core 3.1 的代码
    【解决方案2】:

    对我来说,解决方案 3 有效:https://learn.microsoft.com/en-us/troubleshoot/developer/webapps/iis/health-diagnostic-performance/http-error-405-website

    在 IIS 上转到您的 API 并单击“模块”。从列表中删除 WebDAVModule。

    【讨论】:

      猜你喜欢
      • 2020-10-12
      • 2020-05-02
      • 2021-09-06
      • 1970-01-01
      • 2014-01-12
      • 2012-06-29
      • 2018-05-28
      • 2017-08-29
      • 2016-08-28
      相关资源
      最近更新 更多