且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 ASP.net Core WebAPI 中启用 CORS

更新时间:2022-05-28 23:04:51

因为您有一个非常简单的 CORS 策略(允许来自 XXX 域的所有请求),所以您不需要让它变得如此复杂.首先尝试执行以下操作(CORS 的一个非常基本的实现).

Because you have a very simple CORS policy (Allow all requests from XXX domain), you don't need to make it so complicated. Try doing the following first (A very basic implementation of CORS).

如果您还没有安装 CORS nuget 包.

If you haven't already, install the CORS nuget package.

Install-Package Microsoft.AspNetCore.Cors

在您的 startup.cs 的 ConfigureServices 方法中,添加 CORS 服务.

In the ConfigureServices method of your startup.cs, add the CORS services.

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(); // Make sure you call this previous to AddMvc
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

然后在您的 startup.cs 的配置方法中,添加以下内容:

Then in your Configure method of your startup.cs, add the following :

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // Make sure you call this before calling app.UseMvc()
    app.UseCors(
        options => options.WithOrigins("http://example.com").AllowAnyMethod()
    );

    app.UseMvc();
}

现在试一试.策略适用于您希望针对不同操作(例如,不同主机或不同标头)使用不同策略的情况.对于您的简单示例,您确实不需要它.从这个简单的例子开始,然后根据需要进行调整.

Now give it a go. Policies are for when you want different policies for different actions (e.g. different hosts or different headers). For your simple example you really don't need it. Start with this simple example and tweak as you need to from there.

进一步阅读:http://dotnetcoretutorials.com/2017/01/03/enabling-cors-asp-net-core/