在ASP.NET Core中的GetUserManager的替代方法 [英] Alternate of GetUserManager in asp.net core

查看:116
本文介绍了在ASP.NET Core中的GetUserManager的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将现有的Asp.net Mvc项目转换为.Net Core,现在的问题是此get方法

public ApplicationUserManager UserManager
    {
        get
        {



return _userManager ??
HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

        }
        private set
        {
            _userManager = value;
        }
    }

在Mvc中,我们可以使用

来获取OwinContext

HttpContext.GetOwinContext().GetUserManager()

但是在不存在.Net Core GetOwinContext的情况下,当我比较两个类的HttpContext的定义时

在Mvc中,HttpContextBase是类型,但是在Core中,HttpContext与HttpContextBase在同一命名空间中没有扩展方法,这就是为什么找不到此扩展方法的原因,请让我知道如何在Core中做到这一点? >

解决方案

没有其他选择. ASP.NET Core几乎所有内容都使用依赖项注入.如果需要UserManager<TUser>,则可以将您正在使用的任何类的构造器(控制器等)注入到构造器中:

public class MyController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public MyController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    ...
}

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?

解决方案

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

    ...
}

这篇关于在ASP.NET Core中的GetUserManager的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆