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

查看:232
本文介绍了如何在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属性接受类型为stringpolicyName作为参数:

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?

推荐答案

您必须在应用程序启动时使用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.AllowAnyOrigin()
               .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天全站免登陆