gpt4 book ai didi

c# - ASP.NET Core CORS 请求被阻止;为什么我的 API 没有应用正确的 header ?

转载 作者:行者123 更新时间:2023-12-02 00:03:22 25 4
gpt4 key购买 nike

尝试设置 CORS 并进行身份验证。我有一个 Web API 站点:http://localhost:61000以及一个消费 Web 应用程序位于 http://localhost:62000 。在 Web API Startup.cs 中,我有:

 public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("MyPolicy", corsBuilder =>
{
corsBuilder.WithOrigins("http://localhost:62000")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));
IMvcBuilder builder = services.AddMvc();
// ...
}

// ...

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("MyPolicy");
app.UseDeveloperExceptionPage();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
}

所有文档似乎都表明这应该是我所需要的。在我的应用程序的 Javascript 中,我调用:

    $.ajax({
type: 'POST',
url: "http://localhost:61000/config/api/v1/MyStuff",
data: matchForm.serialize(),
crossDomain: true,
xhrFields: { withCredentials: true },
success: function (data) {
alert(data);
}
});

我进入Chrome:无法加载http://localhost:61000/config/api/v1/MyStuff:请求的资源上不存在“Access-Control-Allow-Origin” header 。因此,不允许访问源“http://localhost:62000”。

...在 Firefox 中:跨源请求被阻止:同源策略不允许读取 http://localhost:61000/config/api/v1/MyStuff 处的远程资源。 (原因:CORS header “Access-Control-Allow-Origin”丢失)。

我错过了什么?我想,这应该是我启用 CORS 所需的全部内容,但显然还缺少其他东西。

最佳答案

对于 ASP.NET Core 2.1 及更早版本:

我的代码中似乎存在错误,但我注意到了模糊的错误,而不是获得 ASP.NET 生成的错误页面。事实证明,CORS header 一开始确实被正确应用,但随后它们就被消除了任何 ASP.NET 中间件生成的错误。另请参阅https://github.com/aspnet/Home/issues/2378 .

我使用该链接来找出这个类

using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace MySite.Web.Middleware
{
/// <summary>
/// Reinstates CORS headers whenever an error occurs.
/// </summary>
/// <remarks>ASP.NET strips off CORS on errors; this overcomes this issue,
/// explained and worked around at https://github.com/aspnet/Home/issues/2378 </remarks>
public class MaintainCorsHeadersMiddleware
{
public MaintainCorsHeadersMiddleware(RequestDelegate next)
{
_next = next;
}
private readonly RequestDelegate _next;

public async Task Invoke(HttpContext httpContext)
{
// Find and hold onto any CORS related headers ...
var corsHeaders = new HeaderDictionary();
foreach (var pair in httpContext.Response.Headers)
{
if (!pair.Key.ToLower().StartsWith("access-control-")) { continue; } // Not CORS related
corsHeaders[pair.Key] = pair.Value;
}

// Bind to the OnStarting event so that we can make sure these CORS headers are still included going to the client
httpContext.Response.OnStarting(o => {
var ctx = (HttpContext)o;
var headers = ctx.Response.Headers;
// Ensure all CORS headers remain or else add them back in ...
foreach (var pair in corsHeaders)
{
if (headers.ContainsKey(pair.Key)) { continue; } // Still there!
headers.Add(pair.Key, pair.Value);
}
return Task.CompletedTask;
}, httpContext);

// Call the pipeline ...
await _next(httpContext);
}
}
}

然后我将其添加到 Startup.cs 中的站点配置中:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(...);
app.UseMiddleware<MaintainCorsHeadersMiddleware>();

...
app.UseMvc();
}

关于c# - ASP.NET Core CORS 请求被阻止;为什么我的 API 没有应用正确的 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49900141/

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