我在OWIN Self-Host Web API中使用带有业务逻辑的服务,我想将当前用户注入此服务。
这是我的IdentityService with CurrentUser属性:
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;
}
}
}
对于自托管的Web API,HttpContext.Current为null,我应该检查一下吗?也许是确定当前用户的更好方法?