繁体   English   中英

MVC Action Filter使用传递给for ActionResult的参数?

[英]MVC Action Filters using parameters passed to the for ActionResult?

我创建了一个没有问题的自定义Action Filter

但我想修改Action Filter以使用实际传递给我的方法的一些参数。

所以,如果我有以下方法:

[HttpPost]
[MyAttribute]
public ActionResult ViewUserDetails(Guid userId)
{
     // Do something
}

如何从MyAttribute访问userId? 有没有办法直接传递它?

您可以尝试使用OnActionExecuting覆盖,您可以在其中访问操作参数。

public class MyAttribute: ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {    
        if (filterContext.ActionParameters.ContainsKey("userId"))
        {
            var userId = filterContext.ActionParameters["userId"] as Guid;
            if (userId != null)
            {
                // Really?! Great!            
            }
        }
    }
} 

您可以创建一个派生自FilterAttribute的自定义属性,并实现IAuthorizationFilter

您还应该能够通过访问filterContext.HttpContext.User.Identity来获取OnAuthorization方法中的用户信息,而无需传递用户标识。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM