如何在 ASP.NET Core 中启用 CORS [英] How to enable CORS in ASP.NET Core

查看:35
本文介绍了如何在 ASP.NET Core 中启用 CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的 ASP.NET Core Web API 上启用跨源资源共享,但我卡住了.

I am trying to enable cross origin resources sharing on my ASP.NET Core Web API, but I am stuck.

EnableCors 属性接受 string 类型的 policyName 作为参数:

The EnableCors attribute accepts policyName of type string as parameter:

// Summary:
//     Creates a new instance of the Microsoft.AspNetCore.Cors.Core.EnableCorsAttribute.
//
// Parameters:
//   policyName:
//     The name of the policy to be applied.
public EnableCorsAttribute(string policyName);

policyName 是什么意思,我如何在 ASP.NET Core Web API 上配置 CORS?

What does the policyName mean and how can I configure CORS on an ASP.NET Core Web API?

推荐答案

对于 ASP.NET Core 6:

For ASP.NET Core 6:

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();

有关更多示例,请参阅官方文档.

See the See the official docs for more samples.

对于 ASP.NET Core 3.1 和 5.0:

For ASP.NET Core 3.1 and 5.0:

您必须在应用程序启动时在 ConfigureServices 方法中配置 CORS 策略:

You have to configure a CORS policy at application startup in the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
    {
        builder.WithOrigins("http://example.com")
               .AllowAnyMethod()
               .AllowAnyHeader();
    }));

    // ...
}

builder 中的 CorsPolicyBuilder 允许您根据需要配置策略.您现在可以使用此名称将策略应用于控制器和操作:

The CorsPolicyBuilder in builder allows you to configure the policy to your needs. You can now use this name to apply the policy to controllers and actions:

[EnableCors("MyPolicy")]

或者将其应用于每个请求:

Or apply it to every request:

public void Configure(IApplicationBuilder app)
{
    app.UseCors("MyPolicy");

    // ...

    // This should always be called last to ensure that
    // middleware is registered in the correct order.
    app.UseMvc();
}

这篇关于如何在 ASP.NET Core 中启用 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆