EnableCors C# .NET Core 3

2020-07-22 18:26发布

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

2条回答
地球回转人心会变
2楼-- · 2020-07-22 18:36

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.

查看更多
相关推荐>>
3楼-- · 2020-07-22 18:51

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());
查看更多
登录 后发表回答