在ASP.NET 5& C中启用跨源请求(CORS) MVC 6 [英] Enable cross-origin requests (CORS) in ASP.NET 5 & MVC 6

查看:685
本文介绍了在ASP.NET 5& C中启用跨源请求(CORS) MVC 6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的MVC 6 WebApi项目中启用CORS,我发现这个问题,重点是同样的问题:


I'm trying to enable CORS in my MVC 6 WebApi project, and I found this question, focusing on the same problem: How do you enable cross-origin requests (CORS) in ASP.NET 5 & MVC 6?

It looks exactly like what I want to do, but when I get to this part, I run into trouble.

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

It (aswell as any other ressources on this subject I have found) clearly states that I should use app.UseCors("policyname") in the Configure method of the Startup.cs-file. But when I do, I get the following error:

'IApplicationBuilder' does not contain a definition for 'UseCors' and no extension method 'UseCors' accepting a first argument of type 'IApplicationBuilder' could be found (are you missing a using directive or an assembly reference?)

I know this is a brand new feature in MVC 6, maybe that explains why I havn't been able to find any official documentation on how to implement this.

Could it be something as simple as adding the correct NuGet package? I've tried several .Net NuGet packages from Microsoft related to CORS, but they didn't solve the problem, and I suspect they are related to the old version of WebApi.

解决方案

Add in this

using Microsoft.AspNet.Builder;

and make sure you have the package in your project.json file

Microsoft.AspNet.Cors.Core

This is an image of the extensions

这篇关于在ASP.NET 5& C中启用跨源请求(CORS) MVC 6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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