MVC相当于Web表单&QUOT的

MVC相当于Web表单&QUOT的

本文介绍了MVC相当于Web表单&QUOT的; UrlAuthorizationModule.CheckUrlAccessForPrincipal"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这样的控制器:

So I have this Controller:

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

  public ActionResult Index()
  {
   ...

正如你所看到的,只有具有管理员角色的用户可以访问myController的的操作方法。

所以,从别的地方的(另一个控制器,在我的图书馆类另一个类,等等) 的我怎么检查的 Current.User.Identity.Name 的访问myController的?


一些作品一样的UrlAuthorizationModule.CheckUrlAccessForPrincipal的对的WebForms。

As you can see, only users with the Administrator role have access to MyController's Action methods.

So, from somewhere else (another controller, another class in my library class, etc) how do I check if Current.User.Identity.Name has access to MyController?

Something that works like "UrlAuthorizationModule.CheckUrlAccessForPrincipal" for WebForms.

推荐答案

您将不得不读取来自其他控制器的信息。这可以通过实例它的背景和描述,然后实例化 AuthorizationContext 该控制器和读取过滤器信息来完成。

You would have to read the information from the other controller. This can be done by instantiating its context and the Descriptor, then instantiating the AuthorizationContext for that controller and read the filter info.

这是你如何能做到这

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;
}

这篇关于MVC相当于Web表单&QUOT的; UrlAuthorizationModule.CheckUrlAccessForPrincipal"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 01:35