webapi跨域实现(CROS、JSONP)

CROS:

    /// 
    /// 支持WebAPI服务器端跨域
    /// 
    public class ServerCrossDomainAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            HttpRequestHeaders requestHeaders = actionExecutedContext.Request.Headers;
            if (requestHeaders.Contains("Origin"))
            {
                string originHeader = requestHeaders.GetValues("Origin").FirstOrDefault();
                if (!string.IsNullOrEmpty(originHeader))
                {
                    HttpResponseHeaders responseHeaders = actionExecutedContext.Response.Headers;
                    responseHeaders.Add("Access-Control-Allow-Origin", originHeader);
                    responseHeaders.Add("Access-Control-Allow-Credentials", "true");
                    actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
                    actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
                }
            }
        }
    }

JSONP:

    /// 
    /// 支持WebAPI客户端跨域,jsonp
    /// 
    public class JSONPAttribute : ActionFilterAttribute
    {
        private const string CALL_BACK_QUERY_PARAMETER = "callback";

        public override void OnActionExecuted(HttpActionExecutedContext context)
        {
            string callback;
            if (IsJsonp(out callback))
            {
                var jsonBuilder = new StringBuilder(callback);
                jsonBuilder.AppendFormat("({0})", context.Response.Content.ReadAsStringAsync().Result);
                context.Response.Content = new StringContent(jsonBuilder.ToString());
            }
            base.OnActionExecuted(context);
        }


        private bool IsJsonp(out string callback)
        {
            callback = HttpContext.Current.Request.QueryString[CALL_BACK_QUERY_PARAMETER];
            return !string.IsNullOrEmpty(callback);
        }
    }

你可能感兴趣的:(webapi跨域实现(CROS、JSONP))