【发布时间】: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();
}
【问题讨论】:
标签: c# angularjs ionic-framework asp.net-web-api cors