关于MVC和身份的两个问题 [英] Two questions about MVC, and Identity
问题描述
我很新的身份和MVC,我想创建一个MVC应用程序作为我的第一个项目之一。
我已经能够遵循<一个href=\"http://typecastexception.com/post/2014/06/22/ASPNET-Identity-20-Customizing-Users-and-Roles.aspx\"相对=nofollow>几个教程并已成功添加附加属性我ApplicationUser:IdentityUser类
公共类ApplicationUser
:IdentityUser&LT;字符串,ApplicationUserLogin,
ApplicationUserRole,ApplicationUserClaim&GT;
{
[需要]
[显示(名称=用户名)]
[StringLength(50)]
公共字符串句柄{搞定;组; } [StringLength(100的ErrorMessage =您的{0}最多只能{1}个字符长。)]
[显示(名称=名)]
公共字符串名字{获得;组; } [StringLength(100的ErrorMessage =您的{0}最多只能{1}个字符长。)]
[显示(名称=姓氏)]
公共字符串名字{获得;组; } [需要]
[显示(名称=用户创建日期)]
公众的DateTime UserCreationDate {搞定;组; } 公共ApplicationUser()
{
。this.Id = Guid.NewGuid()的ToString(); //添加任何自定义用户属性/ code在这里
}
我的问题是:
-
我看到的电子邮件设置为需要App_Start.IdentityConfig.cs唯一的电子邮件,有没有一种方法来设置它需要像处理一个独特的自定义属性?
VAR经理=新ApplicationUserManager(新UserStore&LT; ApplicationUser,ApplicationRole,串,ApplicationUserLogin,ApplicationUserRole,ApplicationUserClaim&GT;(context.Get&LT; ApplicationDbContext&GT;()));
//配置用户名验证逻辑
manager.UserValidator =新UserValidator&LT; ApplicationUser&GT;(经理)
{
AllowOnlyAlphanumericUserNames =假,
RequireUniqueEmail =真
}; -
在Views.Shared._LoginPartial.cshtml的局部视图它显示登录到使用User.Identity.GetUserName(申请的人的用户名/电子邮件)是有参考我的自定义属性的一个途径而是有诸如名字,或办理?
@using Microsoft.AspNet.Identity@if(Request.IsAuthenticated)
{
使用(Html.BeginForm(注销,帐户,FormMethod.Post,新{ID =logoutForm,@class =Navbar的权利}))
{
@ Html.AntiForgeryToken() &LT; UL类=NAV导航栏,导航栏导航右&GT;
&LT;立GT;
@ Html.ActionLink(你好+ User.Identity.GetUserName()+索引,管理,routeValues!:空,htmlAttributes:新{标题=管理})
&LT; /李&GT;
&LT;立GT;&LT; A HREF =JavaScript的:的document.getElementById('logoutForm')提交()&GT;注销&LT; / A&GT;&LT; /李&GT;
&LT; / UL&GT;
}
}
其他
{
&LT; UL类=NAV导航栏,导航栏导航右&GT;
&LT;立GT; @ Html.ActionLink(注册,注册,帐户,routeValues:空,htmlAttributes:新{ID =registerLink})LT; /李&GT;
&LT;立GT; @ Html.ActionLink(登录,登录,帐户,routeValues:空,htmlAttributes:新{ID =LOGINLINK})LT; /李&GT;
&LT; / UL&GT;
}
实现自定义 UserValidator
已经在这里涵盖:<一href=\"http://stackoverflow.com/questions/27655578/how-can-customize-asp-net-identity-2-username-already-taken-validation-message\">How可以自定义Asp.net身份2名已被使用验证消息?
而不是命中为每个页面请求显示处理数据库,登入过程中添加的索赔。
定义你自己的要求:
公共静态类CustomClaimTypes
{
公共常量字符串句柄=http://schemas.xmlsoap.org/ws/2014/03/mystuff/claims/handle;
}
在登入,设置声明:
专用异步任务SignInAsync(ApplicationUser用户,布尔isPersistent,字符串密码= NULL)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); VAR身份=等待UserManager.CreateIdentityAsync(用户,DefaultAuthenticationTypes.ApplicationCookie); //获取手柄,并添加自称的身份。
VAR手柄= GetTheHandle();
identity.AddClaim(新索赔(CustomClaimTypes.Handle,手柄); AuthenticationManager.SignIn(新AuthenticationProperties(){IsPersistent = isPersistent},身份);
}
然后,通过一个扩展方法,你可以读取它的出路一样 GetUserName()
:
公共静态类IdentityExtensions
{
公共静态字符串GetHandle(此的IIdentity身份)
{
如果(身份== NULL)
返回null; 返回(身份ClaimsIdentity).FirstOrNull(CustomClaimTypes.Handle);
} 内部静态字符串FirstOrNull(这ClaimsIdentity身份,串claimType)
{
VAR VAL = identity.FindFirst(claimType); 返回VAL == NULL?空:val.Value;
}
}
最后,在你看来:
@ User.Identity.GetHandle()
I am very new to identity and MVC, I am trying to create an MVC app as one of my first projects.
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
}
My questions are:
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 };
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> }
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.
Define your own claim:
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);
}
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;
}
}
Finally, in your view:
@User.Identity.GetHandle()
这篇关于关于MVC和身份的两个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!