1. 程式人生 > 實用技巧 >服務端跨域四種方式

服務端跨域四種方式

1、自定義方式

····/// <summary>
    /// 支援WebAPI伺服器端跨域
    /// 有很多種支援服務端跨域的方式,但是不能夠同時使用
    /// </summary>
    public class ServerCrossDomainAttribute : ActionFilterAttribute
    {
        private const string ORIGIN = "Origin";
        private const string ACCESS_CONTROL_ALLOW_ORIGIN = "
Access-Control-Allow-Origin"; public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { #region 跨域 if (actionExecutedContext.Request.Headers.Contains(ORIGIN)) { string originHeader = actionExecutedContext.Request.Headers.GetValues(ORIGIN).FirstOrDefault();
if (!string.IsNullOrEmpty(originHeader)) { #region 第一種支援跨域的方式 //actionExecutedContext.Response.Headers.Add(ACCESS_CONTROL_ALLOW_ORIGIN, originHeader); //actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
//actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization"); #endregion #region 第二種支援跨域方式 //actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*"); //actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); //actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization"); #endregion #region 第三種支援跨域方式 在webconfig中配置 //< !--< add name = "Access-Control-Allow-Origin" value = "*" /> //< add name = "Access-Control-Allow-Headers" value = "Content-Type, Authorization" /> //< add name = "Access-Control-Allow-Methods" value = "GET, POST, PUT, DELETE, OPTIONS" /> --> #endregion } } #endregion } }

2、使用System.Web.Http.Cors