我目前正在开发ASP Net Core API,当我尝试向服务器发送PUT请求时,出现返回错误:
对预检请求的响应未通过访问控制检查:所请求的资源上没有“ Access-Control-Allow-Origin”标头
我已经准备好设置app.EnableCors()和services.EnableCors()了,但是即使在那之后,我仍然收到错误消息。
代码如下:
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>();
}
}
Startup.cs看起来像这样:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc(ConfigureMvcOptions);
services.AddSwaggerGen(ConfigureSwaggerOptions);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
app.UseMiddleware(typeof(CorsMiddleware));
app.UseAuthentication();
app.UseMvc();
}
答案 0 :(得分:0)
2天前,我遇到了这个确切的问题。我的解决方案是在需要时使管道短路。我不知道其他中间件会发生什么,但是设置状态码后,其他一些东西会改变状态码。对于选项预检请求,实际上您可能不需要执行任何其他操作。
更改此:
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);
}
答案 1 :(得分:0)
转到您的Startup.cs
文件
在ConfigureServices
方法中添加;
services.AddCors(options =>
{
options.AddPolicy("AllowLocalhost",
builder => builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetPreflightMaxAge(TimeSpan.FromDays(5)));
});
然后在Configure
方法中添加;
app.UseCors("AllowLocalhost");