首页 > 解决方案 > ASP Net Core - 通用页面模型

问题描述

我开始学习使用 ASP Net Core 编程。在花一些时间使用 Asp Net Core Identity 时,我想实现一个自己的登录页面以用于学习目的。不幸的是,如果您想使用包含通用参数(如 Asp Net Core Identity 的 Login.cshtml.cs)的页面模型,我现在有一些问题要了解依赖注入是如何工作的。在源代码中有两个派生自登录页面的页面模型的类:

[AllowAnonymous]
[IdentityDefaultUI(typeof(LoginModel<>))]
public abstract class LoginModel : PageModel

internal class LoginModel<TUser> : LoginModel where TUser : class

我读到 SignInManager 类处理 Identity 中的登录和注销过程。但因此我想我必须使用内部类。但是我不明白 Asp Net Core 标识符是如何使用内部类而不是抽象类的,或者它可以吗?!

即使在剃须刀页面中,也只有抽象类用作模型:

@page
@model LoginModel
@{
ViewData["Title"] = "Log in";
}

有没有人可以向我解释我必须做什么才能像内部 LoginModel 类一样为页面模型使用通用参数?我认为这对于其他一些情况也可能非常有用。

标签: c#genericsasp.net-coreidentityrazor-pages

解决方案


我想我找到了解决问题的方法。内部类似乎由 PageModel 约定初始化,可以在 IdentityPageModelConvention 源文件中找到:

public void Apply(PageApplicationModel model)
    {
        var defaultUIAttribute = model.ModelType.GetCustomAttribute<IdentityDefaultUIAttribute>();
        if (defaultUIAttribute == null)
        {
            return;
        }

        ValidateTemplate(defaultUIAttribute.Template);
        var templateInstance = defaultUIAttribute.Template.MakeGenericType(typeof(TUser));
        model.ModelType = templateInstance.GetTypeInfo();
    }

此方法似乎通过抽象 LoginModel 类中定义的 IdentityDefaultUI 属性确定具有 TUser 通用属性的内部类:

[IdentityDefaultUI(typeof(LoginModel<>))]
public abstract class LoginModel : PageModel

推荐阅读