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;
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
{
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();
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;
//授权的请求域名
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
}
}
}