webapi跨域实现(CROS、JSONP)

Core版CROS:

https://www.cnblogs.com/stulzq/p/9392150.html

CROS:

    /// <summary>
    /// 支持WebAPI服务器端跨域
    /// </summary>
    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:

    /// <summary>
    /// 支持WebAPI客户端跨域,jsonp
    /// </summary>
    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);
        }
    }
原文地址:https://www.cnblogs.com/fanfan-90/p/12049141.html