开发者

Per request code

开发者 https://www.devze.com 2023-04-05 16:24 出处:网络
I have a method, that I want to run once per Http request, but after stuff like Context.Current.User has been assigned.

I have a method, that I want to run once per Http request, but after stuff like Context.Current.User has been assigned.

    public static void AddPrincipal(HttpContext context)
    {
        var users = DependencyResolver.Current.GetService<IRepository<User>>();
        var currentUser = users.Retrieve(u => u.Username == context.User.Identity.Name);
        var principal = new Principal(currentUser);
        context.Items.Add("Principal", principal);
    }

What's the best way to achieve that in ASP.Net MVC3?

I tried to put it in Controller factory, but I have some partials actions on my pages, so It gets run more that once.

I also tried BeginRequest in Global.asax, but HttpContext.Current.User is null at that point of time..

Thanks in ad开发者_如何转开发vance!


First I will say that based upon what you are doing, you might want to look more at something like building a custom MembershipProvider or at the least a custom HttpModule , but to answer your question:

You might try subscribing to the Application_AuthenticateRequest event, which is supposed to be raised after the HttpRequest is finished being authenticated (which should be after the HttpContext.Current.User has been populated)

Do something like this in your Global.asax

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    AddPrinciple(HttpContext.Current);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号