Lea*_*sed 15 c# asp.net-mvc owin asp.net-identity
我使用Asp.net的身份进行登录,注册,忘记密码等和源代码从该采取以下链接:
现在我有一个UserMaster表,在注册期间我要求以下字段: FullName,EmailId,Password,ContactNumber,Gender.
我的UserMaster包含以下字段:Id,FullName,EmailId,ContactNumber,Gender
现在,当用户提交注册表格时,此FullName,EmailId,ContactNumber,Gender将与电子邮件一起保存在UserMaster中,密码将保存在AspnetUser中.
我的注册方法与上面2个链接中提供的相同.
在这里您可能会注意到我的UserMaster和AspnetUser之间没有任何关系,所以在登录时用户将输入他的电子邮件ID登录我将使用此方法await SignInManager.PasswordSignInAsync验证用户,如果此方法返回成功,那么我将要使用此电子邮件ID并在我的UserMaster中检查此电子邮件,并找到匹配的地方我将从UserMaster获取UserId并将其存储在会话中并使用我的登录方法使用我的应用程序,如下所示:
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
using (var context = new MyEntities())
{
var fetchUSerId = context.UserMaster.Where(t => t.Email == model.Email).Select(t=>t.UserId).SingleOrDefault();
Session["UserId"] = fetchUSerId;
}
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
Run Code Online (Sandbox Code Playgroud)
我在登录方法中谈论这个:
case SignInStatus.Success:
using (var context = new MyEntities())
{
var fetchUSerId = context.UserMaster.Where(t => t.Email == model.Email).Select(t=>t.UserId).SingleOrDefault();
Session["UserId"] = fetchUSerId;
}
Run Code Online (Sandbox Code Playgroud)
这是一种合适的方式还是更好的方式,我想存储整个用户对象而不是仅存储用户ID.
所以有人能告诉我如何使用aspnet身份吗?
Bre*_*een 28
由于您使用的是Asp.Net Identity,因此您希望将与会话相关的内容存储为声明.通过定制声明,这很容易扩展.
顺便说一下,我认为你最好还是简单地扩展ApplicationUser来保存额外的数据,详见此处.
也就是说,这是一个如何向您的应用程序添加自定义声明类型的完整示例.
第1步 - 定义一个或多个自定义声明类型以保存您的其他信息
public static class CustomClaimTypes
{
public const string MasterFullName = "http://schemas.xmlsoap.org/ws/2014/03/mystuff/claims/masterfullname";
public const string MasterUserId = "http://schemas.xmlsoap.org/ws/2014/03/mystuff/claims/masteruserid";
}
Run Code Online (Sandbox Code Playgroud)
声明类型只是一个标识特定声明的唯一字符串.这里我们使用与内置声明类型类似的格式.
第2步 - 在登录过程中,设置自定义声明类型的值
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
//Fetch data from the UserMaster table
var userdata = GetdatafromUserMaster();
//Using the UserMaster data, set our custom claim types
identity.AddClaim(new Claim(CustomClaimTypes.MasterUserId, userdata.UserId));
identity.AddClaim(new Claim(CustomClaimTypes.MasterFullName, userdata.FullName));
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
Run Code Online (Sandbox Code Playgroud)
注意:我们使用自定义声明类型,以便保留现有声明NameIdentifier和Name声明,因此可以轻松地从Asp.Net Identity 和我们的自定义UserMaster表中访问身份信息.
第3步 - 添加扩展方法,IIdentity以便我们可以轻松访问我们的自定义声明数据
public static class IdentityExtensions
{
public static string GetMasterUserId(this IIdentity identity)
{
if (identity == null)
return null;
return (identity as ClaimsIdentity).FirstOrNull(CustomClaimTypes.MasterUserId);
}
public static string GetMasterFullName(this IIdentity identity)
{
if (identity == null)
return null;
return (identity as ClaimsIdentity).FirstOrNull(CustomClaimTypes.MasterFullName);
}
internal static string FirstOrNull(this ClaimsIdentity identity, string claimType)
{
var val = identity.FindFirst(claimType);
return val == null ? null : val.Value;
}
}
Run Code Online (Sandbox Code Playgroud)
没什么好看的.我们只是将IIdentitya作为a ClaimsIdentity,然后返回CustomClaimType我们找到的给定的第一个声明的值,或者null如果声明不存在则返回.
第4步 - 现在我们可以非常轻松地访问视图和/或控制器中的自定义声明数据.假设您想使用UserMaster表中的全名而不是ApplicationUser?你现在可以这样做:
<ul class="nav navbar-nav navbar-right">
<li>
@Html.ActionLink("Hello " + User.Identity.GetMasterFullName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)
您也可以在Controller中执行相同的操作.
| 归档时间: |
|
| 查看次数: |
14642 次 |
| 最近记录: |