EnableCors C#.NET Core 3 [英] EnableCors C# .NET Core 3

查看:315
本文介绍了EnableCors C#.NET Core 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#API,并从前端执行GET请求,为实现这一点,我需要在我的API中启用cors,但我似乎做不到!

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!

这是.NET Core 3 API,我尝试遵循教程,我也尝试安装

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

但是在执行GET请求时仍然出现cors错误.

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

尝试使用 [EnableCors] 批注时,出现一条错误消息,提示找不到EnableCorsAttribute" ...

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

我还添加了

app.UseCors();

进入我的Startup.cs,但没有运气.

to my Startup.cs but with no luck.

任何帮助将不胜感激!

编辑-粘贴在此处的Startup.cs : https://pastebin.com/pCLSh3Tf

编辑-此处粘贴控制器: https://pastebin.com/mUSfvNR0

推荐答案

不确定Core 3.0中是否有任何更改,但是在2.2中,我会这样解决:将其添加到ConfigureServices

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

还请确保您在Configure方法中添加策略:

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

app.UseCors("CorsPolicy");

如果要使用cors,则可以编辑该策略,因为这实际上是将其禁用.

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

这篇关于EnableCors C#.NET Core 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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