Reputation: 5191
I am converting an existing Asp.net Mvc project to .Net Core now the issue is this get method
public ApplicationUserManager UserManager
{
get
{
return _userManager ??
HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
In Mvc we could fetch OwinContext using
HttpContext.GetOwinContext().GetUserManager()
but in case of .Net Core GetOwinContext not present , When I compare definition of HttpContext of both classes
HttpContextBase is type in case of Mvc but in case of Core there is HttpContext which has no extension method in same namespace as HttpContextBase that's why this extension method was not found ,Please let me know how to do this in Core?
Upvotes: 2
Views: 3558
Reputation: 29986
For accessing UserManager
from HttpContext
, you could try to implement an extension like below:
public static class HttpContextExtension
{
public static UserManager<TUser> GetUserManager<TUser>(this HttpContext context) where TUser: class
{
return context.RequestServices.GetRequiredService<UserManager<TUser>>();
}
}
And then use it like
public class HomeController : Controller
{
public IActionResult Index()
{
var userManager = HttpContext.GetUserManager<IdentityUser>();
return View();
}
}
Upvotes: 2
Reputation: 239290
There is no alternate. ASP.NET Core uses dependency injection for pretty much everything. If you need UserManager<TUser>
, you inject into the constructor of whatever class you're working with (controller, etc.):
public class MyController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
public MyController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
...
}
Upvotes: 4