gpt4 book ai didi

.NET 6 API : Access-Control-Allow-Origin missing from response header

转载 作者:行者123 更新时间:2023-12-02 07:32:39 26 4
gpt4 key购买 nike

我有一个在 Azure AD 上注册的 .NET 6 Web API,如图所示 here 。我也有registered一个调用我的 API 并处理身份验证的 Web 应用程序。我可以使用它来获取 token ,然后在 Postman 中使用它向我的 API 发送请求。

现在有一个 React 应用程序(由另一个团队开发)应该是我的 API 的前端。我正在尝试在本地设置整个应用程序,我的 API 正在监听 localhost:5220,而 React 应用程序正在 localhost:3001 上运行。当我尝试发送请求时,出现以下错误:enter image description here

错误信息:

Access to fetch at 'http://localhost:5220/api/job/all' from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

GET http://localhost:5220/api/job/all net::ERR_FAILED 307

这些是我的标题:

enter image description here

这是我的 Program.cs 的一部分:

if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseRequestLocalization(localizationOptions);
app.UseCors(options => options.WithOrigins("http://localhost:3001").AllowAnyHeader().AllowAnyMethod().AllowCredentials());
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

我发现这是中间件所需的顺序,如果我删除 UseHttpsRedirection 或将其放在 UseCors 之后,我会收到 401 错误,但随后 Access- Control-Allow-Origin header 出现在响应中。我已安装 Microsoft.AspNetCore.Cors NuGet 包,但它呈灰色显示。

这是我的 launchSettings.json 中的 applicationUrl:

"applicationUrl": "https://localhost:7220;http://localhost:5220"

我做错了什么?我应该如何配置 API 以发回正确的 header ?为什么我的代码不使用 using Microsoft.AspNetCore.Cors 指令?

编辑:事实证明,前端应用程序没有发送 access_token,但现在它已更新,因此我会收到每个请求的 token (并且 token 在 Postman 中工作),但我仍然面临与上述相同的问题。当我从 launchSettings 中删除 HttpsRedirection 和 localhost:7220 时,我仍然收到 401 Unauthorized 错误,但我还在日志中收到此消息:

[2023-01-19 13:02:24.112 +02:00 INF] Authorization failed. These requirements were not met:

DenyAnonymousAuthorizationRequirement: Requires an authenticated user.

ScopeAuthorizationRequirement:Scope=

[2023-01-19 13:02:24.114 +02:00 INF] AuthenticationScheme: Bearerwas challenged.

有人可以告诉我为什么这不起作用吗?

最佳答案

在startup.cs文件上尝试一次,

  1. 创建全局变量

    公共(public)字符串MyAllowSpecificOrigins =“_myAllowSpecificOrigins”;

  2. 在ConfigureService函数内部写入

    services.AddCors(c =>{c.AddPolicy(MyAllowSpecificOrigins, 选项 =>选项.AllowAnyOrigin());});

  3. 然后在配置函数中,使用下面的行。

    app.UseCors(MyAllowSpecificOrigins);

现在运行您的应用程序。

关于.NET 6 API : Access-Control-Allow-Origin missing from response header,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75106987/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com