了解 ActionFilterAtrribute 中的 ActionExecutingContext.Result

问题描述 投票:0回答:1

我最近阅读了这段代码,它使 MVC Web API 允许 CORS(跨源资源共享)。我知道

ActionFilterAtrribute
使它成为一个过滤器,但我不确定这个类中发生了什么:
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
,我们会做一些我在这种情况下不太理解的事情。否则,我们会做一些我也不确定的事情吗?

这里到底发生了什么?

c# asp.net-mvc cross-domain actionfilterattribute onactionexecuting
1个回答
1
投票

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

如果您覆盖

OnActionExecuting
功能,它允许您在执行控制器操作之前执行任何特定代码。对于你的情况:

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

如果请求是

HttpOPTIONS
,则在执行控制器操作之前,代码会向客户端返回一个空响应。

如果请求是其他类型:

else
{
    base.OnActionExecuting(filterContext);
}

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

© www.soinside.com 2019 - 2024. All rights reserved.