【问题标题】:Read non primitive ActionParameters from filterContext in ActionFilter从 ActionFilter 中的 filterContext 读取非原始 ActionParameters
【发布时间】:2012-03-26 22:43:42
【问题描述】:

我目前正在开发一个 ASP.NET MVC 项目。

我想实现一个 ActionFilter,它负责所有权权限。用户只能访问与他在数据库中关联的实体。

现在我不想在每个控制器中实现这一点。相反,我想使用 ActionFilter。 我已经可以识别传入参数并使用以下代码读取它们的值:

控制器

[Validate(ParameterName = "userID", EntityType="User")]
public ActionMethod Edit(int userID){...

动作过滤器

public string ParameterName { get; set; }
public string EntityType { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
    if (EntityType != null && ParameterName != null)
    {
        Debug.Print("Checking if user has access to the Type \"" + EntityType + "\" with the
ID " + filterContext.ActionParameters[ParameterName]);
...

到目前为止,这工作正常。但是当涉及到非原始类型(例如 User)时,我只在 filterContext.ActionParameters[ParameterName]) 中找到了一个 NULL 值;

[HttpPost]
[Validate(ParameterName = "user", EntityType = "User")]
public ActionResult Edit(User user)
{....

我不知道为什么。难道是因为这是一个HttpPost方法?

【问题讨论】:

    标签: asp.net-mvc action-filter


    【解决方案1】:

    假设您从ActionFilterAttribute 派生并且尚未实现IAuthorizationFilter,这应该可以工作,因为如果您实现此接口,则操作过滤器将在模型绑定器之前运行,您将无法获得此模型的结果binder,只有简单的 HTTP 请求值。这是一个例子:

    public class User
    {
        public string FirstName { get; set; }
    }
    

    验证属性:

    public class ValidateAttribute : ActionFilterAttribute
    {
        public string ParameterName { get; set; }
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var result = (User)filterContext.ActionParameters[ParameterName];
            if (result.FirstName == "john")
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
    }
    

    控制器:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new User
            {
                FirstName = "john"
            });
        }
    
        [HttpPost]
        [Validate(ParameterName = "user")]
        public ActionResult Index(User user)
        {
            return View(user);
        }
    }
    

    查看:

    @model User
    
    @using (Html.BeginForm())
    {
        @Html.EditorFor(x => x.FirstName)
        <button type="submit">OK</button>
    }
    

    【讨论】:

    • 这正是我正在寻找的答案!我在同一个类中实现了 IAuthorizationFilter 和 ActionFilterAttribute 。现在我把它们分开了——效果很好!非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 2012-02-11
    • 2015-12-30
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多