【问题标题】:Understanding ActionExecutingContext.Result within an ActionFilterAtrribute使用 ActionFilterAttribute 了解 ActionExecutingContext.Result
【发布时间】:2016-02-07 08:35:01
【问题描述】:

我最近阅读了这段代码,它使 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】:

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

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

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

    如果请求是HttpOPTIONS,那么在执行控制器操作之前,代码会向客户端返回一个空响应。

    如果请求是其他类型的:

    else
    {
        base.OnActionExecuting(filterContext);
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多