问题描述
我想与MVC 6,但目前所有的文档构建的API,使CORS参考早期版本的框架。
I'd like to enable CORS on an API built with MVC 6 but all the current documents refer to earlier versions of that framework.
推荐答案
在新的一个Cors特征的笔记很轻,但我可以通过看新的类和方法得到它在我的解决方案的工作。我的Web API的 startup.cs 看起来是这样的。你可以看到如何通过使用新的 CorsPolicy
类构造你的出身和她的政策。和启用的 AddCors
和 UseCors
方法CORS。
The notes on the new Cors features are very light, but I was able to get it working in my solution by looking at the new classes and methods. My Web API startup.cs looks like this. You can see how you can construct your origins and policies her by using the new CorsPolicy
class. And enabling CORS with the AddCors
and UseCors
methods.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//Add Cors support to the service
services.AddCors();
var policy = new Microsoft.AspNet.Cors.Core.CorsPolicy();
policy.Headers.Add("*");
policy.Methods.Add("*");
policy.Origins.Add("*");
policy.SupportsCredentials = true;
services.ConfigureCors(x=>x.AddPolicy("mypolicy", policy));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Configure the HTTP request pipeline.
app.UseStaticFiles();
//Use the new policy globally
app.UseCors("mypolicy");
// Add MVC to the request pipeline.
app.UseMvc();
}
您还可以像这样的新属性引用策略中的控制器
You can also reference the policy in the controllers with the new attributes like so
[EnableCors("mypolicy")]
[Route("api/[controller]")]
这篇关于你如何启用ASP.NET 5和跨域请求(CORS); MVC 6?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!