asp.net-mvc - 为什么模型绑定(bind)比过滤器更早发生

标签 asp.net-mvc authorization model-binding action-filter

看完这篇优秀的博客post通过 Simon,我知道模型绑定(bind)发生在过滤器执行之前(甚至在授权过滤器之前)。如果请求未获得授权,则应尽早拒绝它,在这种情况下,我更喜欢在模型绑定(bind)过程之前运行授权过滤器。此外,通过这种方式,我们可以节省时间,避免扫描请求、创建模型实例和执行验证。

有什么理由我根本不明白为什么 MVC 请求处理管道的设计方式是模型绑定(bind)应该在过滤器之前发生?

最佳答案

在 asp.net mvc3 中,授权过滤器在模型绑定(bind)之前执行,而不是之后(参见下面的代码)。

模型绑定(bind)发生在过滤器之前,因为 ActionExecutingContext(IActionFilter.OnActionExecuting 的参数)包含操作的参数。也许他们应该延迟加载这些参数。

以下代码来自 System.Web.Mvc.ControllerActionInvoker。

public virtual bool InvokeAction(ControllerContext controllerContext, string actionName) 
{
    // code removed for brevity
    try 
    {
        // Notice the authorization filters are invoked before model binding
        AuthorizationContext authContext = InvokeAuthorizationFilters(controllerContext, filterInfo.AuthorizationFilters, actionDescriptor);
        if (authContext.Result != null) {
            // the auth filter signaled that we should let it short-circuit the request
            InvokeActionResult(controllerContext, authContext.Result);
        }
        else {
            if (controllerContext.Controller.ValidateRequest) {
                ValidateRequest(controllerContext);
            }
            // GetParameterValues does the model binding
            IDictionary<string, object> parameters = GetParameterValues(controllerContext, actionDescriptor);
            ActionExecutedContext postActionContext = InvokeActionMethodWithFilters(controllerContext, filterInfo.ActionFilters, actionDescriptor, parameters);
            InvokeActionResultWithFilters(controllerContext, filterInfo.ResultFilters, postActionContext.Result);
        }
    }
    // code removed for brevity
}

关于asp.net-mvc - 为什么模型绑定(bind)比过滤器更早发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13765393/

相关文章:

c# - 如何发布包含 Iformfile 的 View 模型数组的表单?

MongoDB 3.2 身份验证失败

c# - 模型绑定(bind)到 ASP.NET MVC 3 中的枚举

c# - 为什么 HTML.TextArea 之前需要一个@?

asp.net-mvc - POST 后丢失 ViewModel 数据

c# - 带有自定义属性的 DropDownListFor - 在属性名称中?

asp.net-mvc - 如何更改 ASP.NET MVC 中的默认验证错误消息?

authorization - 我在 openshift 上遇到授权 token 问题

c# - WCF:配置角色以访问数据库资源

c# - 是否可以有一个可用于模型绑定(bind)的非公共(public)无参数构造函数?