了解 ActionFilterAtribute 中的 ActionExecutingContext.Result

Understanding ActionExecutingContext.Result within an ActionFilterAtrribute

我最近阅读了这段代码,它使 MVC Web API 允许 CORS(跨源资源共享)。我知道 ActionFilterAtrribute 使它成为一个过滤器,但我不确定 class 中发生了什么:AllowCORS.

public class AllowCORS : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if(filterContext.HttpContext.Request.HttpMethod == "OPTIONS")
        {
            filterContext.Result = new EmptyResult();
        }
        else
        {
            base.OnActionExecuting(filterContext);
        }
    }
}

所以基本上,如果我们收到的请求方法是 HttpOPTIONS,我们会做一些我不太了解的事情。否则,我们会做一些我也不确定的事情吗?

有没有人帮忙详细说说,到底是怎么回事?

ActionFilterAttribute class 中,OnActionExecuting 在执行放置 ActionFilterAttribute 属性的控制器操作之前执行。

如果您覆盖OnActionExecuting函数,它允许您在执行控制器操作之前执行任何特定代码。你的情况:

if(filterContext.HttpContext.Request.HttpMethod == "OPTIONS")
{
    filterContext.Result = new EmptyResult();
}

如果请求是 HttpOPTIONS,那么在执行控制器操作之前,代码 return 是对客户端的空响应。

如果请求是其他类型:

else
{
    base.OnActionExecuting(filterContext);
}

它将允许执行控制器操作并return响应客户端。