/// <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

            
        }
    }

二、使用System.Web.Http.Cors

.NET Framework 服务端跨域四种方式

 

相关文章:

  • 2021-12-16
  • 2021-06-26
  • 2022-12-23
  • 2021-08-14
  • 2021-07-14
  • 2022-12-23
  • 2022-12-23
  • 2021-10-01
猜你喜欢
  • 2021-12-10
  • 2021-10-19
  • 2021-09-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案