MVC Action Filter使用传递给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方法中的用户信息,而无需传递用户标识。