【问题标题】:Base Controller inheritance in ASP.NET Core identityASP.NET Core 标识中的基本控制器继承
【发布时间】:2019-09-23 09:36:10
【问题描述】:

我刚刚在 asp net core 中开始了我的第一个项目,并从 .Net 框架迁移。

我使用 ASP.NET Core 2.1 创建了一个新项目,并通过

添加了标识
Right click on project -> Add -> Add scaffolded items

到我的项目。

首先有些事情让我感到困惑。所有用于识别的文件都移到了一个名为“身份”的区域,而“管理”部分文件也移到了“帐户”文件夹中。最重要的是我没有帐户和管理控制器

我创建了一个名为 BaseController 的新空控制器:

public class BaseController : Controller
{
    private ApplicationDbContext _db { get; set; }

    public BaseController(ApplicationDbContext db)
    {
        _db = db;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (HttpContext.User.Identity.IsAuthenticated)
        {
            string userEmail = User.Identity.Name;                
            ViewBag.CurrentUser = _db.Users.Where(u => u.Email.Equals(userEmail)).FirstOrDefault();
        }

        base.OnActionExecuting(filterContext);
    }
}

在此控制器中,我获取登录用户并将其传递给 ViewBag 并在我的视图中显示。

我有一个继承自 BaseControllerHomeController

public class HomeController : BaseController
{
    private UserManager<ApplicationUser> _userManager { get; set; }
    private readonly ApplicationDbContext _db;

    public HomeController(UserManager<ApplicationUser> userManager, 
                          ApplicationDbContext db) : base (db)
    {
        _userManager = userManager;
        _db = db;
    }

    public IActionResult Index()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}

这部分代码工作正常,但是当我尝试导航到 Manage/IndexManage/ChangePassword 时,我收到了这个错误,我不知道如何解决这个问题。此错误的原因是 ViewBag 为空,因为基本控制器操作从未运行。

对不起,如果我的问题很简单而且不专业

【问题讨论】:

  • 您确定身份验证正在进行吗?除非控制器需要身份验证,否则可能不会设置 HttpContext.User.Identity.IsAuthenticated,因此没有 ViewBag 值。将 [Authorize] 属性添加到控制器方法或控制器类将强制对请求进行身份验证,这将设置用户身份。
  • @Rentering.com 在家庭控制器身份验证工作。当我在导航栏菜单上启动项目时,我可以看到我的授权电子邮件和全名,我也可以注销。

标签: c# asp.net-core .net-core


【解决方案1】:

在asp.net core 2.1中,scaffold Identity使用Razor Pages而不是MVC结构,所以Identity区域没有控制器,不能继承控制器。参考here

由于在区域内,您需要使用 https://localhost:44367/Identity/Account/Manage/Indexhttps://localhost:44367/Identity/Account/Manage/ChangePassword 之类的 URL 来访问 Razor 页面。

此外,Razor 页面不支持ViewBag,您可以改用ViewData,参考here

为 Razor 页面添加过滤器,您可以参考Filters in Razor Pages

public class BasePageModel : PageModel
{
    public override void OnPageHandlerExecuting(PageHandlerExecutingContext context)
    {
        //...
    }
}
public class IndexModel : BasePageModel
{
    public void OnGet()
    {
        //...
    }
}

【讨论】:

  • 非常感谢@Xing_Zou。非常感谢您的帮助。
  • @Xing_Zou 关于 ViewData 的观点很好,我错过了关于 ViewBag 的那个非常重要的观点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多