【问题标题】:How to call controller method in global.asax?如何在 global.asax 中调用控制器方法?
【发布时间】:2014-02-23 08:18:36
【问题描述】:

我想在 Global.asax 中调用控制器方法。代码如下。

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
    {
        if (User.Identity.IsAuthenticated)
        {      
            //here we can subscribe user to a role via Roles.AddUserToRole()
        }
    }

此事件在 global.asax 中。我想调用从数据库返回用户权限的控制器方法。在我将用户权限保存在会话和我的控制器构造函数中之后,这怎么可能在这里调用控制器方法?代码如下。

public class AccountController : Controller
{

    private readonly ISecurityService securityService;

    public AccountController(ISecurityService securityService)
    {
        this.securityService = securityService;
    }
}

请指导我。

【问题讨论】:

  • 我会将用户权限分离到一个单独的类中,并让控制器和 global.asax 调用该类。我会避免你的 global.asax 和你的控制器之间有任何依赖关系,因为你最终可能会陷入无限循环。
  • 请你给我任何例子@Rob Lang 吗?

标签: c# asp.net asp.net-mvc asp.net-mvc-4 asp.net-mvc-5


【解决方案1】:

您可以使用自定义 AuthorizeAttribute 来处理此问题。这允许您将一个属性放置在您需要身份验证才能成功调用的任何控制器/方法的顶部。这使您可以覆盖AuthorizeCore,然后您可以使用它来执行您想要执行的任何自定义授权。您还可以通过此方法将任何其他信息保存到会话。

例如:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // do your own athorization stuff here
    }
}

然后您可以使用您的属性来装饰需要使用此授权的控制器:

[CustomAuthorize]
public class AccountController : Controller
{
}

或者使用基本控制器:

[CustomAuthorize]
public class BaseAuthController : Controller
{
}

public class AccountController : BaseAuthController
{
}

【讨论】:

    【解决方案2】:

    我自己解决这个问题我通过解决依赖问题在global.asax中调用服务方法下面是上述问题的解决方案。

    protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            if (User.Identity.IsAuthenticated)
            {
                IUnityContainer container = GetUnityContainer();
                ISecurityService securityService = container.Resolve<SecurityService>();
                var list = securityService.GetUserRolesandPermissions("1");
            }
        }
    

    谢谢大家。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-29
      • 2017-02-22
      相关资源
      最近更新 更多