在dotnet core web api中支持CORS(跨域访问)
问题描述:
需要提前设置好cors,设置好cors后,get或者post(pain/text)这些简单类型都可以请求。
但是,
需要对服务器进行非简单请求时,比如context-type为json时,第一次会发送option方法探测,第二次才会正式发送post请求,由于webapi未开启option方法,前端会收到204错误(204 No Content),post也就没发出去。
解决方法:
通过中间间,对option方法进行启用,并回应200状态码。
设置cors,具体做法:
步骤1.在startup.cs 的ConfigureServices方法中加入
services.AddCors(Options =>
Options.AddPolicy("543",
p => p.AllowAnyOrigin())
);// 代码写在mvc前面
// services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
步骤2.在startup.cs 的Configure方法中加入
app.UseCors("543");// 代码写在mvc前面
//app.UseMvc();
设置cors 完毕。
开启option方法,具体做法:
步骤1. 创建一个OptionsMiddleware.cs类
步骤2. 复制代码进去
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace xxxxxxxxx
{
public class OptionsMiddleware
{
private readonly RequestDelegate _next;
public OptionsMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext context)
{
return BeginInvoke(context);
}
private Task BeginInvoke(HttpContext context)
{
if (context.Request.Method == "OPTIONS")
{
context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { (string)context.Request.Headers["Origin"] });
context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept" });
context.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" });
context.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });
context.Response.StatusCode = 200;
return context.Response.WriteAsync("OK");
}
return _next.Invoke(context);
}
}
public static class OptionsMiddlewareExtensions
{
public static IApplicationBuilder UseOptions(this IApplicationBuilder builder)
{
return builder.UseMiddleware<OptionsMiddleware>();
}
}
}
步骤3.在startup.cs 的Configure方法中加入
app.UseOptions(); // 在方法最开始的位置加,其他位置没测试。
开启option方法,设置完毕。