Enable cross-origin requests (CORS) in ASP.NET 5 & MVC 6

不问归期 提交于 2020-01-05 08:23:38

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/31851028/enable-cross-origin-requests-cors-in-asp-net-5-mvc-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!