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

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

问题描述

我试图启用跨起源资源共​​享我的ASP.NET 5 API,但我卡住了。

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

EnableCors 属性接受 policyName 类型字符串作为参数:

The EnableCors attribute accepts policyName of type string as parameter:

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



什么的 policyName 的含义及如何能我配置的 CORS 上的ASP.NET 5 API?

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

推荐答案

您必须配置一个CORS政策在该 ConfigureServices 方法,应用程序的启动:

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

    // ...
}



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

    // ...
}

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

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