C# .net MVC处理跨域的过滤器

/// <summary>
/// 处理跨域的过滤器
/// </summary>
public class AllowCrossSiteAttribute: ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
       HttpResponseBase response = filterContext.HttpContext.Response;

    // 设置允许的来源(你可以替换 "*" 为具体的域名,例如 "https://example.com")
    response.AddHeader("Access-Control-Allow-Origin", "*");
    
   
    // 如果是 OPTIONS 请求,直接返回 200 状态码
    if (filterContext.HttpContext.Request.HttpMethod == "OPTIONS")
    {
        filterContext.Result = new HttpStatusCodeResult(200);
    }

    base.OnActionExecuted(filterContext);
    }
}

 

posted @ 2025-05-26 08:38  曲琦  阅读(7)  评论(0)    收藏  举报