ASP Net Core-通用页面模型

时间:2019-06-22 01:07:19

标签: c# generics asp.net-core identity razor-pages

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

[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类一样对页面模型使用通用参数?我认为这在其他一些情况下也可能非常有用。

1 个答案:

答案 0 :(得分:0)

我认为我找到了解决问题的方法。 内部类似乎是由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 Attribute确定具有TUser泛型属性的内部类:

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