简体   繁体   中英

How to inject User Identity in Asp.Net web api controller constructor?

I have a controller decorated with [Authorize] attribute. I would like to accomplish the following so that I don't have to repeatedly create repository obj and pass currentUser in each method:

[Authorize]
public class HomeController : ApiController
{
    Repository repo;     

    public HomeController()
    {
        var userName = User.Identity.IsAuthenticated ? User.Identity.Name : null;

        repo = new Repository(userName);

    }           

}

I know User.Identity is not available in constructor or in Initialize method. What is the best practice to inject authenticated user in controller constructor.

If we use dependency injection - while registering our custom created UserResolverService inside WebApiConfig.cs in Register method - User.Identity is not available at this point as well.

This is a very common issue with web api but somehow couldn't find any article showing proper solution.

Is it really achievable and if yes - can you please provide some sample code?

Here is how I worked around this (not sure how appropriate this method is, but it works).

In your BaseContoller (a controller from which all other controllers inherit from) create instance of Repository like so:

private Repository _Repository;
private Repository Repository
{
    get 
    {
        _Repository.InjectUsername(User.Identity.Name); // value is already available here
        return _Repository;
    }
    set
    {
        _Repository = new Repository();
    }
}

Notice how your Repository has InjectUsername method. That method will simple assign passed parameter to some Repository's property, like so:

public class Repository
{
    private string Username { get; set; }

    public void InjectUsername(string username)
    {
        Username = username;
    }
}

Every time you will call some method in repository from a controller action you will inject usrename which will already exist, and you won't have to duplicate code by passing username to every method in repository every time you call it.

You can register a factory delegate and get user identity from HttpContext.Current .

Here's a sample code for simpleinjector

container.Register<IPrincipal>(() => HttpContext.Current.User);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM