Question: How do you get user id in .net core MVC from a service repository?
Login to See the Rest of the Answer
Answer: The User's Id can be obtained from .net core application in several ways, one of them is by getting User from an HttpContext:
//This an Interface
namespace YourProjectName.FirstLevelFolder.FinalFolderYourInterfaceClassIsLocated
{
public interface IUserUtility
{
Task<string> GetUserID();
}
}
?
//This is a Service Mock Repository Class that implements IUserUtility Interface
namespace ProjectName.FolderName
{
public class UserUtilityRepository : IUserUtility
{
private readonly SignInManager<AnotherUserMockRepositoryClass> _signInManager;
private readonly HttpContext _contextRequest;
public UserUtilityRepository(SignInManager<AnotherUserMockRepositoryClass> signInManager, HttpContext contextRequest)
{
_signInManager = signInManager;
_contextRequest = contextRequest;
}
public async Task<string> GetUserID()
{
ClaimsPrincipal principal = _contextRequest.User as ClaimsPrincipal;
string UserID = _signInManager.UserManager.GetUserId(principal);
return UserID;
}
}
}
?
An unhandled exception occurred while processing the request.