放置请求期间的 ASP Net Core CORS 错误

Posted

技术标签:

【中文标题】放置请求期间的 ASP Net Core CORS 错误【英文标题】:ASP Net Core CORS error during put request 【发布时间】:2019-03-10 05:50:49 【问题描述】:

我目前正在开发一个 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();
 

【问题讨论】:

【参考方案1】:

我在 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);
    

【讨论】:

谢谢 Lee O。但即使在那之后我仍然遇到同样的错误。 service.UseCors() 不应该是必需的。您的自定义中间件不依赖于任何已注册的服务。此外,您的扩展方法没有被调用,但您在 app.UseMiddleware(typeof(CorsMiddleware));您可以将其替换为 app.UseCorsMiddleware(); 如果您在这些更改后仍然遇到问题,我会尝试通过 Postman 或其他没有预检选项请求的方式访问端点,看看您是否仍然获得 500。【参考方案2】:

转到您的Startup.cs 文件

ConfigureServices方法中添加;

services.AddCors(options =>

    options.AddPolicy("AllowLocalhost",
    builder => builder
    .AllowAnyOrigin()
    .AllowAnyHeader()
    .AllowAnyMethod()
    .AllowCredentials()
    .SetPreflightMaxAge(TimeSpan.FromDays(5)));
);

然后在Configure方法中添加;

app.UseCors("AllowLocalhost");

【讨论】:

谢谢 mojoblanco,但是在我添加这个之后,我得到一个 No 'Access-Control-Allow-Origin' 标头出现在请求的资源上。响应的 HTTP 状态代码为 500。 错误 这里有同样的问题。该解决方案似乎没有任何区别。据我所知,它应该工作,但它没有。

以上是关于放置请求期间的 ASP Net Core CORS 错误的主要内容,如果未能解决你的问题,请参考以下文章