关于MVC和Identity的两个问题 [英] Two questions about MVC, and Identity

查看:23
本文介绍了关于MVC和Identity的两个问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对身份和 MVC 非常陌生,我正在尝试创建一个 MVC 应用程序作为我的第一个项目.

I am very new to identity and MVC, I am trying to create an MVC app as one of my first projects.

我已经能够关注 一些教程 并成功地向我的 ApplicationUser 添加了额外的属性:IdentityUser 类

I have been able to follow a few tutorials and have successfully added additional properties to my ApplicationUser : IdentityUser class

public class ApplicationUser
    : IdentityUser<string, ApplicationUserLogin,
    ApplicationUserRole, ApplicationUserClaim>
{
    [Required]
    [Display(Name = "UserName")]
    [StringLength(50)]
    public string Handle { get; set; }

    [StringLength(100, ErrorMessage = "Your {0} can be at most {1} characters long.")]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [StringLength(100, ErrorMessage = "Your {0} can be at most {1} characters long.")]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [Required]
    [Display(Name = "User Creation Date")]
    public DateTime UserCreationDate { get; set; }

    public ApplicationUser()
    {
        this.Id = Guid.NewGuid().ToString();

        // Add any custom User properties/code here
    }

我的问题是:

  1. 我看到在 App_Start.IdentityConfig.cs 中电子邮件被设置为需要唯一的电子邮件,有没有办法将其设置为需要像 Handle 这样的唯一自定义属性?

  1. I see where Email is set to require a unique Email in App_Start.IdentityConfig.cs, Is there a way to set it up to require a unique custom property like Handle?

    var manager = new ApplicationUserManager(new UserStore<ApplicationUser, ApplicationRole, string, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>(context.Get<ApplicationDbContext>()));
    // Configure validation logic for usernames
    manager.UserValidator = new UserValidator<ApplicationUser>(manager)
    {
        AllowOnlyAlphanumericUserNames = false,
        RequireUniqueEmail = true
    };

  • 在 Views.Shared._LoginPartial.cshtml 的部分视图中,它显示了使用 User.Identity.GetUserName() 登录应用程序的人的用户名/电子邮件是否有办法引用我的自定义属性之一取而代之的是 FirstName 或 Handle?

  • In the Partial View of Views.Shared._LoginPartial.cshtml it shows the UserName/Email of the person logging into the application using User.Identity.GetUserName() is there a way to reference one of my custom properties there instead such as FirstName, or Handle?

    @using Microsoft.AspNet.Identity
    
    @if (Request.IsAuthenticated)
    {
        using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
        {
        @Html.AntiForgeryToken()
    
        <ul class="nav navbar-nav navbar-right">
            <li>
                @Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
            </li>
            <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
        </ul>
        }
    }
    else
    {
        <ul class="nav navbar-nav navbar-right">
            <li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
            <li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
        </ul>
    }
    

  • 推荐答案

    实现自定义 UserValidator 已在此处介绍:如何自定义 Asp.net Identity 2 用户名已获取验证消息?

    Implementing a custom UserValidator has already been covered here: How can customize Asp.net Identity 2 username already taken validation message?

    与其为每个页面请求都访问数据库以显示句柄,不如在登录期间添加声明.

    Rather than hitting the database for every page request to display the handle, add a claim during signin.

    定义您自己的声明:

    public static class CustomClaimTypes
    {
        public const string Handle = "http://schemas.xmlsoap.org/ws/2014/03/mystuff/claims/handle";
    }
    

    在登录期间,设置声明:

    During signin, set the claim:

    private async Task SignInAsync(ApplicationUser user, bool isPersistent, string password = null)
    {
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    
        var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
    
        //Get the handle and add the claim to the identity.
        var handle = GetTheHandle();
        identity.AddClaim(new Claim(CustomClaimTypes.Handle, handle);
    
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
    }
    

    然后,通过一个扩展方法,你可以像GetUserName()一样读出它:

    Then, via an extension method you can read it out the same way as GetUserName():

    public static class IdentityExtensions
    {
        public static string GetHandle(this IIdentity identity)
        {
            if (identity == null)
                return null;
    
            return (identity as ClaimsIdentity).FirstOrNull(CustomClaimTypes.Handle);
        }
    
        internal static string FirstOrNull(this ClaimsIdentity identity, string claimType)
        {
            var val = identity.FindFirst(claimType);
    
            return val == null ? null : val.Value;
        }
    }
    

    最后,在您看来:

    @User.Identity.GetHandle()
    

    这篇关于关于MVC和Identity的两个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆