重写Controller Initialize方法
protected override void Initialize(System.Web.Routing.RequestContext requestContext) {
if (requestContext.HttpContext.Response != null) {
//跨域支持
var host = requestContext.HttpContext.Request.Headers["Host"];
var Requestorigin = requestContext.HttpContext.Request.Headers["Origin"];
var origin = "*";
origin = Requestorigin;
if (string.IsNullOrEmpty(origin) && !string.IsNullOrEmpty(host))
origin = "http://" + host;
var originUrl = requestContext.HttpContext.Request.Url;
if (origin == "*" && originUrl != null)
origin = $"{originUrl.Scheme}://+{originUrl.Authority}";
requestContext.HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", origin);
requestContext.HttpContext.Response.AppendHeader("Access-Control-Allow-Credentials", "true");
requestContext.HttpContext.Response.AppendHeader("Access-Control-Allow-Headers", "Content-Type");
requestContext.HttpContext.Response.AppendHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
}
//拦截OPTIONS,返回200状态
if (requestContext.HttpContext.Request.HttpMethod == "OPTIONS") {
requestContext.HttpContext.Response.StatusCode = 200;
requestContext.HttpContext.Response.End();
return;
}
base.Initialize(requestContext);
}