У меня есть служба UserContext, в которую я добавлю некоторые основные функции ("IsAuthenticated
, GetUser
и т. д.).
Для этого мне нужно передать HTTPContext
из моего контроллера WebAPI в мою службу библиотеки классов.
На самом деле, HttpContext
всегда null
в контроллере веб-API.
У кого-нибудь есть решение моей проблемы? Есть ли лучший способ добиться этого.
Контроллер пользователей веб-API
[Route("api/[controller]")]
[Authorize]
public class UserController : Controller
{
private readonly IUserContextServices _userContextServices;
private readonly User loggedUser;
public UserController()
{
//HttpContext ALWAYS NULL
_userContextServices = new UserContextService(HttpContext);
}
}
Службы пользовательского контекста
namespace MyProj.Services
{
public interface IUserContextServices
{
UserContext GetUserContext();
bool IsUserAuthenticated();
}
public class UserContextService : IUserContextServices
{
private readonly HttpContext _context;
private UserContext _userContext;
public UserContextService(HttpContext context)
{
_context = context;
InitUserContext();
}
private IEnumerable<Claim> GetUserClaims()
{
if (IsUserAuthenticated())
{
return _context.User.Claims;
}
return null;
}
private void InitUserContext()
{
if (IsUserAuthenticated())
{
var claims = GetUserClaims();
_userContext = new UserContext();
_userContext.Email = claims.First(p => p.Type == "email").Value;
_userContext.AspNetUserID = claims.First(p => p.Type == "sub").Value;
}
}
public UserContext GetUserContext()
{
return _userContext;
}
public bool IsUserAuthenticated()
{
return _context.User != null && _context.User.Identity != null && _context.User.Identity.IsAuthenticated;
}
}
}