简体   繁体   中英

ASP Net Core - Generic Page Models

I am starting to learn programming with ASP Net Core. While spending some time with Asp Net Core Identity I wanted to implement a own Login Page for learning purposes. Unfortunately now I have some issue to understand how the dependency injection works if you want to use a Page Model which includes a generic parameter like Login.cshtml.cs of Asp Net Core Identity does. In the source code there are two classes which derives from Page Model for the Login Page:

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

and

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

I read that the SignInManager class handels the sign in and out process in Identity. But therefore I guess I have to use the internal class. But I do not understand how Asp Net Core identifiers to use the internal class instead of the abstract one or maybe it does?!

Even in the razor page only the abstract class is used as the model:

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

Is there anyone who can explain me what I have to do to be able to use a generic parameter for a page model like the internal LoginModel class does? I think this could be very useful for some other cases, too.

I think I found the solution for my problem. The internal class seems to be initialised by a PageModel convention which can be found in the IdentityPageModelConvention source file:

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

This method seems to determine the internal class with TUser generic property by the IdentityDefaultUI Attribute which is defined in the abstract LoginModel class:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM