如何从HttpContextBase获取ActionExecutingContext

时间:2011-01-17 17:35:41

标签: asp.net-mvc-2 authorization

我正在努力实现自定义的AuthorizeAttribute。 AuthorizeCore覆盖接受HttpContextBase。如果用户没有正确的角色,那么我想抛出一个错误。我找到了一些代码,我可以设置MasterName,ViewName等来重定向用户。它使用ActionExecutingContext:

private void ThrowError(ActionExecutingContext filterContext, string message)
  {
   var ex = new Exception(message);
   var errorInfo = new HandleErrorInfo(ex, filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, filterContext.ActionDescriptor.ActionName);
   var viewData = new ViewDataDictionary(errorInfo);

   filterContext.Result = new ViewResult { MasterName = MasterName, ViewName = ViewName, ViewData = viewData };
  }

是否可以从HttpContextBase中获取ActionExecutingContext传递给AuthorizeCore覆盖?如果没有,有什么建议吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

AuthorizeCore方法中,您无需执行任何重定向。您只需使用Http Context返回true或false,具体取决于用户是否经过身份验证和授权。为了将他重定向到错误页面,您需要覆盖HandleUnauthorizedRequest方法,其中AuthorizationContext作为参数传递,您可以处理该案例。 <{1}}返回AuthorizeCore时会调用此方法,以便您可以采取相应的行动。