ASP.NET Core CORS请求被阻止;我的API为什么不应用正确的标头? [英] ASP.NET Core CORS request blocked; why doesn't my API apply the right headers?
问题描述
尝试通过身份验证设置CORS.我在 http://localhost:61000 上有一个Web API网站,在
Trying to set up CORS with authentication. I have a Web API site up at http://localhost:61000 and a consuming web application up at http://localhost:62000. In the Web API Startup.cs, I have:
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中,我调用:
All the doucmentation seems to indicate that should be all I need. In my app's Javascript, I call:
$.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:Failed to load http://localhost:61000/config/api/v1/MyStuff: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:62000' is therefore not allowed access.
And I get in Chrome: Failed to load http://localhost:61000/config/api/v1/MyStuff: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:62000' is therefore not allowed access.
...以及Firefox中的Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:61000/config/api/v1/MyStuff. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
...and in Firefox: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:61000/config/api/v1/MyStuff. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
我想念什么?我认为,这应该是我启用CORS所需要的,但是显然还有其他地方缺少.
What am I missing? This should be all I need to enable CORS, I thought, but clearly there is something else missing.
推荐答案
对于ASP.NET Core 2.1和更早版本:
似乎我的代码中有错误,但是我注意到了一个晦涩的错误,而不是得到一个ASP.NET生成的错误页面.事实证明,CORS标头确实确实是一开始就正确应用的,但随后除去了ASP.NET中间件生成的任何错误.另请参见 https://github.com/aspnet/Home/issues/2378 .
It seems there was an error in my code, but I got the obscure error noted instead of getting an ASP.NET-generated error page. It turns out that the CORS headers are indeed properly applied at first, but then they are stripped off any ASP.NET middleware-generated errors. See also https://github.com/aspnet/Home/issues/2378 .
我使用该链接来找出此类
I used that link to figure out this class
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的站点配置中:
And then I added it to my site configuration in Startup.cs:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(...);
app.UseMiddleware<MaintainCorsHeadersMiddleware>();
...
app.UseMvc();
}
这篇关于ASP.NET Core CORS请求被阻止;我的API为什么不应用正确的标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!