且构网

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

你如何启用ASP.NET 5和跨域请求(CORS); MVC 6?

更新时间:2023-02-15 19:09:13

在新的一个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]")]