1

所以我有这个控制器:

namespace MyNamespace.Controllers
{
  [Authorize(Roles="Administrator")]
  public class MyController : Controller

  public ActionResult Index()
  {
   ...

如您所见,只有具有管理员角色的用户才能访问 MyController 的 Action 方法。

那么,从其他地方(另一个控制器、我的库类中的另一个类等)如何检查Current.User.Identity.Name是否有权访问 MyController?

类似于WebForms 的“UrlAuthorizationModule.CheckUrlAccessForPrincipal”的东西。

4

1 回答 1

1

您必须从另一个控制器读取信息。这可以通过实例化其上下文和描述符来完成,然后AuthorizationContext为该控制器实例化并读取过滤器信息。

这是你可以做到的

private bool ActionIsAccessibleToUser(string actionName, ControllerBase controllerBase)
{
    // Get controller context.
    var controllerContext = new ControllerContext(this.ControllerContext.RequestContext, controllerBase);

    // Get controller descriptor.
    var controllerDescriptor = new ReflectedControllerDescriptor(controllerBase.GetType());

    // Get action descriptor.
    var actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);

    // Check on authorization.
    return ActionIsAuthorized(actionDescriptor, controllerContext);
}

private bool ActionIsAuthorized(ActionDescriptor actionDescriptor, ControllerContext controllerContext)
{
    if (actionDescriptor == null)
    {
        // Action does not exist.
        return false;
    }

    // Get authorization context fo controller.
    AuthorizationContext authContext = new AuthorizationContext(controllerContext, actionDescriptor);

    // run each auth filter until on fails
    // performance could be improved by some caching
    var filters = FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor);
    FilterInfo filterInfo = new FilterInfo(filters);

    foreach (IAuthorizationFilter authFilter in filterInfo.AuthorizationFilters)
    {
        // Attempt authorization.
        authFilter.OnAuthorization(authContext);

        // If result is non-null, user is not authorized.
        if (authContext.Result != null)
        {
            return false;
        }
    }

    // Assume user is authorized.
    return true;
}
于 2013-09-26T21:04:38.063 回答