首页 > 解决方案 > 如何在我的 .Net Core Web API 中完全消除 CORs 错误?

问题描述

我在使用 .Net Core 3.1 的 IIS 服务器上有一个 Web api。

它使用的 IP 和端口:http: //68.181.207.10 :8473

我还有 3 个在同一 IIS 服务器上运行的 Web 应用程序。其中 2 个应用程序是 .Net 4.7 应用程序,1 个是 .Net Core 应用程序。

3 个 Web 应用程序都使用 Web api。

这 3 个应用程序是:

https://meta.astro.usc.edu(端口 443)

http://old.astro.perl.edu(80 端口)

http://68.181.207.10(80端口)

我已将 API 设置为使用 COR,并且在大多数情况下,一切正常,并且它们连接到 API 没有任何问题。

但是有时即使我添加了所有需要的 URL,我仍然会遇到 CORs 错误。

在我的 ConfigureServices 方法的顶部,我添加了需要访问的 URL,如下所示:

public void ConfigureServices(IServiceCollection services)
{

    services.AddCors(options =>
    {
        options.AddPolicy(MyAllowSpecificOrigins,
        builder =>
        {
            builder.WithOrigins("http://68.181.207.10:8473", "https://meta.astro.usc.edu", "http://old.astro.perl.edu", "http://68.181.207.10")
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        });
    });
    
    
}

然后在我的配置方法中,我添加app.UseCors如下所示:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }
    app.UseRouting();
    app.UseCors(MyAllowSpecificOrigins);
    app.UseHttpsRedirection();
    app.UseMvc();
}

这是允许这些其他网络应用程序连接到我的网络 API 的正确方法吗?

CORs 错误似乎是随机的,其来源始终是我的 3 个 Web 应用程序之一。一个似乎不会导致比另一个更多的错误。

如何防止我仍然收到的间歇性 COR 错误?

谢谢!

标签: asp.net-coreiisentity-framework-coreasp.net-core-webapi.net-core-3.1

解决方案


检查有问题的请求中的内部服务器错误 (500)


推荐阅读