I am using services with business logic in my OWIN Self-Host Web API, and I want to inject current user to this services.
This is my IdentityService with CurrentUser property:
public class IdentityService : IIdentityService
{
private readonly UserManager<User, int> userManager;
public IdentityService(UserManager<User, int> userManager)
{
if (userManager == null)
{
throw new ArgumentNullException("userManager");
}
this.userManager = userManager;
}
public User CurrentUser
{
get
{
var identity = Thread.CurrentPrincipal;
if (identity == null || identity.Identity == null || !identity.Identity.IsAuthenticated)
{
if (HttpContext.Current == null || HttpContext.Current.User == null)
{
return null;
}
identity = HttpContext.Current.User;
}
var user = this.userManager.FindByName(identity.Identity.Name);
return user;
}
}
}
For self-hosted Web API HttpContext.Current is null, so should I check it? Perhaps is better way to determine the current user?