using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Filters;json
namespace MBT.WebKit.Filter
{
/// <summary>
/// 跨域過濾器
/// author:cza
/// date:2018-08-20
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class OriginWebAttribute : Attribute //: ActionFilterAttribute
{
//存儲key的,未用到
public string AttributeKey = string.Empty;
public OriginWebAttribute()
{
}跨域
/// <summary>
/// 跨域返回消息頭的判斷
/// author:cza
/// date:2018-08-20
/// </summary>
/// <param name="actionContext"></param>
public void OriginActionExecuted(System.Web.Http.Controllers.HttpActionContext actionContext) //System.Web.Http.Controllers.HttpControllerContext ControllerContext
{app
System.Web.Http.Routing.IHttpRouteData data = actionContext.ControllerContext.RouteData;
//針對controller
var allowAnonymous = actionContext.ControllerContext.ControllerDescriptor.ControllerType.CustomAttributes.SingleOrDefault(m => m.AttributeType.Name == typeof(OriginWebAttribute).Name);
if (allowAnonymous == null)
{
//針對某個方法
Type controllerType = actionContext.ControllerContext.ControllerDescriptor.ControllerType.Assembly.GetTypes().Where(m => m.Name.ToLower() == data.Values["Controller"].ToString().ToLower() + "controller").FirstOrDefault();
var attributes = controllerType.GetMethods().Where(m => m.Name.ToLower() == data.Values["Action"].ToString().ToLower()).FirstOrDefault();spa
var allowAnonymousMethods = attributes.CustomAttributes.SingleOrDefault(m => m.AttributeType.Name == typeof(OriginWebAttribute).Name);
if (allowAnonymousMethods == null)
{
return;
}
}
#region 跨域的解決辦法增長返回消息頭
System.Uri uriReferrer = actionContext.ControllerContext.Request.Headers.Referrer;
if (uriReferrer != null)
{
string Origin = uriReferrer.Scheme + "://" + uriReferrer.Host;
int Hostport = uriReferrer.Port;
if (Hostport != 80 && Hostport != 443)
{
Origin = Origin + ":" + Hostport;
}
//沒有返回Response消息頭的話,不要返回,由於reponse爲null的話,證實異常,會走全局捕獲。
if (actionContext.Response != null)
{
//var package = PackageKit.GetResponsePackage<string>(null, 301, "");
//string json = JsonConvert.SerializeObject(package);
//actionContext.Response = new System.Net.Http.HttpResponseMessage();
//StringContent Content = new StringContent(json, Encoding.GetEncoding("UTF-8"), "application/json");
//actionContext.Response.StatusCode = HttpStatusCode.OK;
//actionContext.Response.Content = Content;ip
//受權的請求域名
actionContext.Response.Headers.Add("Access-Control-Allow-Origin", Origin);
actionContext.Response.Headers.Add("Access-Control-Allow-Methods", "*"); //GET,POST,PUT,DELETE,OPTIONS
actionContext.Response.Headers.Add("Access-Control-Allow-Headers", "x-requested-with");
actionContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
}
}
#endregion
}
}
}get
而後在ApiController或對應的方法加上這個自定義屬性就能夠了string