C# 在put请求期间ASP Net核心CORS错误
我目前正在开发ASP Net Core API,当我尝试向服务器发送PUT请求时,返回错误: 对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许来源”标头 我已经准备好设置app.EnableCors()和services.EnableCors(),但即使在这之后,我仍然会收到错误消息 代码如下:C# 在put请求期间ASP Net核心CORS错误,c#,angularjs,ionic-framework,asp.net-web-api,cors,C#,Angularjs,Ionic Framework,Asp.net Web Api,Cors,我目前正在开发ASP Net Core API,当我尝试向服务器发送PUT请求时,返回错误: 对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许来源”标头 我已经准备好设置app.EnableCors()和services.EnableCors(),但即使在这之后,我仍然会收到错误消息 代码如下: public class CorsMiddleware { private readonly RequestDelegate _next; public Cors
public class CorsMiddleware
{
private readonly RequestDelegate _next;
public CorsMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Accept-Encoding, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name");
context.Response.Headers.Add("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");
if (context.Request.Method == "OPTIONS")
{
context.Response.StatusCode = (int)HttpStatusCode.OK;
await context.Response.WriteAsync(string.Empty);
}
await _next(context);
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class CorsMiddlewareExtensions
{
public static IApplicationBuilder UseCorsMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CorsMiddleware>();
}
}
我两天前遇到了这个问题。我的解决方案是在选项请求时使管道短路。我不知道在另一个中间件中发生了什么,但是在您设置状态代码之后,其他一些东西正在改变状态代码。实际上,对于options飞行前请求,您可能不需要任何其他东西来执行 更改此项:
if (context.Request.Method == "OPTIONS")
{
context.Response.StatusCode = (int)HttpStatusCode.OK;
await context.Response.WriteAsync(string.Empty);
}
await _next(context);
为此:
if (context.Request.Method == "OPTIONS")
{
context.Response.StatusCode = (int)HttpStatusCode.OK;
await context.Response.WriteAsync(string.Empty);
}
else
{
await _next(context);
}
转到您的
Startup.cs
文件
在ConfigureServices
方法中添加
services.AddCors(options =>
{
options.AddPolicy("AllowLocalhost",
builder => builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetPreflightMaxAge(TimeSpan.FromDays(5)));
});
app.UseCors("AllowLocalhost");
然后在Configure
方法中添加
services.AddCors(options =>
{
options.AddPolicy("AllowLocalhost",
builder => builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetPreflightMaxAge(TimeSpan.FromDays(5)));
});
app.UseCors("AllowLocalhost");
谢谢你,Lee O。但即使在那之后,我仍然会遇到同样的错误。应该不需要service.UseCors()。您的自定义中间件不依赖于任何已注册的服务。此外,您的扩展方法没有被调用,但您正在执行它在app.useMidleware(typeof(corsmidleware))中所做的操作;你可以用app.UseCorsMiddleware()替换它;如果您在这些更改后仍然遇到问题,我会尝试通过邮递员或其他方式在没有飞行前选项请求的情况下点击端点,看看您是否仍然获得500。谢谢mojoblanco,但在我添加此项后,我会发现请求的资源上没有“Access Control Allow Origin”标头。响应的HTTP状态代码为500。这里也有同样的问题。这个解决方案似乎没有任何区别。在我看来,它应该会起作用,但它不会。