【问题标题】:ASP Net Core - Generic Page ModelsASP Net Core - 通用页面模型
【发布时间】:2019-11-04 19:13:07
【问题描述】:

我开始学习使用 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# generics asp.net-core identity razor-pages


    【解决方案1】:

    我想我找到了解决问题的方法。 内部类似乎是由 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-16
      • 2020-12-21
      • 2020-08-30
      • 1970-01-01
      • 2019-12-05
      • 2019-12-20
      • 2021-02-04
      • 2019-11-22
      相关资源
      最近更新 更多