EnableCors C# .NET Core 3

孤街醉人 提交于 2020-05-12 02:41:55

问题


I'm working on a C# API and doing a GET request from my frontend and for that to happen I need to enable cors in my API, but I can't seem to do it!

It's a .NET Core 3 API and I've tried following this tutorial and I've also tried installing the 2.2 NuGet Package for it via:

dotnet add package Microsoft.AspNetCore.Cors --version 2.2.0

But I still get a cors error when doing my GET request.

When trying the [EnableCors] annotation I get an error saying "The EnableCorsAttribute could not be found"...

I've also added

app.UseCors();

to my Startup.cs but with no luck.

Any help would be greatly appreciated!

Edit - Startup.cs pasted here: https://pastebin.com/pCLSh3Tf

Edit - Controller pasted here: https://pastebin.com/mUSfvNR0


回答1:


Unsure if anything changed in Core 3.0, but in 2.2 I would solve it like this: add this to ConfigureServices

services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());
        });

Also make sure you add your policy in the Configure method:

app.UseCors("CorsPolicy");

You can edit the policy if you want to use cors, since this is basically disabling it.




回答2:


Add the following at the beginning of ConfigureServices:

services.AddCors();

Add the following at the beginning of Configure:

app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());


来源:https://stackoverflow.com/questions/58432870/enablecors-c-sharp-net-core-3

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