void Application_BeginRequest(object sender, EventArgs e) { // 允许跨域请求的域名列表,可以根据需求进行修改 string[] allowedOrigins = new string[] { "http://example1.com", "http://example2.com" }; // 获取请求来源 string origin = HttpContext.Current.Request.Headers["Origin"]; // 检查请求来源是否在允许的域名列表中 if (!string.IsNullOrEmpty(origin) && allowedOrigins.Contains(origin)) { // 设置允许跨域的响应头 HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", origin); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true"); } // 处理预检请求(OPTIONS 请求) if (HttpContext.Current.Request.HttpMethod == "OPTIONS") { HttpContext.Current.Response.StatusCode = 200; HttpContext.Current.Response.End(); } }
要允许所有,使用下面代码 :
Response.AppendHeader("Access-Control-Allow-Origin", "*"); // 允许来自任何域的请求 Response.AppendHeader("Access-Control-Allow-Methods", "POST"); // 允许的请求方法 Response.AppendHeader("Access-Control-Allow-Headers", "Content-Type"); // 允许的请求头
标签:Control,Access,asp,跨域,Response,Current,Allow,net,HttpContext From: https://www.cnblogs.com/nanfei/p/17307671.html