Alternate of GetUserManager in asp.net core

空扰寡人 提交于 2020-01-05 08:34:08

问题


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?


回答1:


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;
    }

    ...
}



回答2:


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();
    }       
}


来源:https://stackoverflow.com/questions/58097042/alternate-of-getusermanager-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!