asp.net mvc设置允许跨域

asp.net mvc设置允许跨域

 public class ApiDataController : Controller
    {
        /// 
        /// 解决跨域
        /// 
        /// 
        protected override void Initialize(RequestContext requestContext)
        {
            /*
             Access to XMLHttpRequest 
            at 'http://localhost:8025/ApiData/GetLeaderboardDeptCurrentMonth?date=2023-8-11' 
            from origin 'http://localhost:8134' 
            has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
             */
            var response = requestContext.HttpContext.Response;
            bool right = requestContext.HttpContext.Request.HttpMethod == "OPTIONS";
            if (right)
            {
                //支持跨域
                response.AddHeader("Access-Control-Allow-Methods", "*");
                response.AddHeader("Access-Control-Allow-Headers", "*");
                response.AddHeader("Access-Control-Allow-Origin", "*");
                response.AddHeader("Cache-Control", "no-cache");
                response.StatusCode = 200;
                response.End();
            }
            else
            {
                response.AddHeader("Access-Control-Allow-Origin", "*");
                response.AddHeader("Access-Control-Allow-Headers", "*");
                response.AddHeader("Access-Control-Allow-Methods", "*");
                response.AddHeader("Cache-Control", "no-cache");
            }
            base.Initialize(requestContext);
            Url = new UrlHelper(requestContext);
        }


}

你可能感兴趣的:(ASP.NET,MVC,asp.net)