User User in ASP.NET MVC 2

I am trying to implement a custom object in ASP.NET MVC 2. I saw a solution where you can do the magic in Global.asax to include Controller.User in another type, like CustomUser. But Controller.User is still IPrincipal, which means I have to pass it to CustomUser every time I want to use it, and I don't like it at all.

Would it be wrong or bad practice to have a basic controller with the GetUser () method, where GetUser () calls the user repository and uses Controller.User to retrieve our own user user object?

What I'm trying to do is just add a few properties to the user object.

+3
source share
3 answers

Would it be a mistake or bad practice to have a base controller with the GetUser () method, where GetUser () calls the user repository and uses Controller.User to get its own custom object?

I do not think so. So I do it.;)

+1
source

Here is what I will do:

In global.asax.cs

protected void Application_PostAuthorizeRequest()
{
    if (HttpContext.Current.User != null && HttpContext.Current.User.Identity != null && !string.IsNullOrEmpty(HttpContext.Current.User.Identity.Name))
    {
        HttpContext.Current.Items["User"] = userRepo.FetchByUsername(HttpContext.Current.User.Identity.Name);
    }
}

public static CustomUser CurrentUser
{
    get
    {
        return HttpContext.Current.Items["User"] as CustomUser;
    }
}

then you have a convenient static code with the current user. This is a dirty but effective way to do this.

Of course, indeed, I would add the user to my IOC container and inject it into my controllers using the ControllerFactory controller with IOC support. This is the right thing.

, ! , , , "" , .

+1

This is the way to do it, however you would like to minimize the amount needed to apply the user object to minimize the violation of the Liskov replacement principle: http://en.wikipedia.org/wiki/Solid_%28object-oriented_design% 29th

Instead of throwing it every time, can't you bury it in ActionFilter?

0
source

Source: https://habr.com/ru/post/1756553/


All Articles