如何使用 asp.net mvc 从头开始添加用户角色
Posted
技术标签:
【中文标题】如何使用 asp.net mvc 从头开始添加用户角色【英文标题】:how to add a user role from scratch using asp.net mvc 【发布时间】:2020-06-11 10:27:19 【问题描述】:我想从头开始创建用户角色和身份,而不是使用创建个人身份验证 ASP.NET MVC 项目时给定的默认值。当我研究时,我会得到在项目中使用默认连接的项目。当我从头开始创建注册和登录时,我实际上不知道在哪里或如何添加角色。
以下是我所做的:
控制器
public class RegistrationController : Controller
//Registration Action
[HttpGet]
public ActionResult Registration()
return View();
//Registration Post Action
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Registration([Bind(Exclude = "IsEmailVerified,ActivationCode")] Customer user)
bool Status = false;
string message = "";
//
// Model Validation
if (ModelState.IsValid)
#region //Email is already Exist
var isExist = IsEmailExist(user.EmailId);
if (isExist)
ModelState.AddModelError("EmailExist", "Email already exist");
return View(user);
#endregion
#region Generate Activation Code
user.ActivationCode = Guid.NewGuid();
#endregion
#region Password Hashing
user.Password = Crypto.Hash(user.Password);
user.ConfirmPassword = Crypto.Hash(user.ConfirmPassword); //
#endregion
user.IsEmailVerified = false;
#region Save to Database
using (mymodel dc = new mymodel())
user.CustomerId = Guid.NewGuid();
dc.Customers.Add(user);
dc.SaveChanges();
//Send Email to User
SendVerificationLinkEmail(user.EmailId, user.ActivationCode.ToString());
message = " Registration successfully done. Account activation link " +
" has been sent to your email: " + user.EmailId;
Status = true;
#endregion
else
message = "Invalid Request";
ViewBag.Message = message;
ViewBag.Status = Status;
return View(user);
//Verify Account
[HttpGet]
public ActionResult VerifyAccount(string id)
bool Status = false;
using (mymodel dc = new mymodel())
dc.Configuration.ValidateOnSaveEnabled = false; // This line I have added here to avoid
// Confirm password does not match issue on save changes
var v = dc.Customers.Where(a => a.ActivationCode == new Guid(id)).FirstOrDefault();
if (v != null)
v.IsEmailVerified = true;
dc.SaveChanges();
Status = true;
else
ViewBag.Message = "Invalid Request";
ViewBag.Status = Status;
return View();
//Login
[HttpGet]
public ActionResult Login()
return View();
//Login Post
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(UserLogin login, string ReturnUrl = "")
string message = "";
using (mymodel dc = new mymodel())
var v = dc.Customers.Where(a => a.EmailId == login.EmailId).FirstOrDefault();
if (v != null)
if (!v.IsEmailVerified)
ViewBag.Message = "Please verify your email first";
return View();
if (string.Compare(Crypto.Hash(login.Password), v.Password) == 0)
int timeout = login.RememberMe ? 525600 : 20; // 525600 min = 1 year
var ticket = new FormsAuthenticationTicket(login.EmailId, login.RememberMe, timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = DateTime.Now.AddMinutes(timeout);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
if (Url.IsLocalUrl(ReturnUrl))
return Redirect(ReturnUrl);
else
return RedirectToAction("Index", "Request");
else
message = "Invalid credential provided";
else
message = "Invalid credential provided";
ViewBag.Message = message;
return View();
//Logout
[Authorize]
[HttpPost]
public ActionResult Logout()
FormsAuthentication.SignOut();
return RedirectToAction("Login", "Registration");
[NonAction]
public bool IsEmailExist(string emailID)
using (mymodel dc = new mymodel())
var v = dc.Customers.Where(a => a.EmailId == emailID).FirstOrDefault();
return v != null;
//Verify Email Link
[NonAction]
public void SendVerificationLinkEmail(string emailID, string activationCode, string emailFor = "VerifyAccount")
var verifyUrl = "/Registration/" + emailFor + "/" + activationCode;
var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, verifyUrl);
var fromEmail = new MailAddress("example@gmail.com", "Lifestyle Laundry");
var toEmail = new MailAddress(emailID);
var fromEmailPassword = "****"; // Replace with actual password
string subject = "";
string body = "";
if (emailFor == "VerifyAccount")
subject = "Your account is successfully created";
body = "<br/><br/>We are excited to tell you that your account is" +
" successfully created. Please click on the below link to verify your account" +
" <br/><br/><a href='" + link + "'>" + link + "</a> ";
else if (emailFor == "ResetPassword")
subject = "Reset Password";
body = "Hi,<br/><br/>We got request for reset your account password. Please click on the below link to reset your password" +
"<br/><br/><a href=" + link + ">Reset Password link</a>";
var smtp = new SmtpClient
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromEmail.Address, fromEmailPassword)
;
using (var message = new MailMessage(fromEmail, toEmail)
Subject = subject,
Body = body,
IsBodyhtml = true
)
smtp.Send(message);
[HttpGet]
public ActionResult ForgotPassword()
return View();
[HttpPost]
public ActionResult ForgotPassword(string EmailID)
//Verify Email ID
//Generate Reset password link
//Send Email
string message = "";
bool status = false;
using (mymodel dc = new mymodel())
var account = dc.Customers.Where(a => a.EmailId == EmailID).FirstOrDefault();
if (account != null)
//Send email for reset password
string resetCode = Guid.NewGuid().ToString();
SendVerificationLinkEmail(account.EmailId, resetCode, "ResetPassword");
account.ResetPasswordCode = resetCode;
//This line I have added here to avoid confirm password not match issue , as we had added a confirm password property
//in our model class in part 1
dc.Configuration.ValidateOnSaveEnabled = false;
dc.SaveChanges();
message = "Reset password link has been sent to your email.";
else
message = "Account not found";
ViewBag.Message = message;
return View();
public ActionResult ResetPassword(string id)
//Verify the reset password link
//Find account associated with this link
//redirect to reset password page
if (string.IsNullOrWhiteSpace(id))
return HttpNotFound();
using (mymodel dc = new mymodel())
var user = dc.Customers.Where(a => a.ResetPasswordCode == id).FirstOrDefault();
if (user != null)
ResetPasswordModel model = new ResetPasswordModel();
model.ResetCode = id;
return View(model);
else
return HttpNotFound();
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ResetPassword(ResetPasswordModel model)
var message = "";
if (ModelState.IsValid)
using (mymodel dc = new mymodel())
var user = dc.Customers.Where(a => a.ResetPasswordCode == model.ResetCode).FirstOrDefault();
if (user != null)
user.Password = Crypto.Hash(model.NewPassword);
user.ResetPasswordCode = "";
dc.Configuration.ValidateOnSaveEnabled = false;
dc.SaveChanges();
message = "New password updated successfully";
else
message = "Something invalid";
ViewBag.Message = message;
return View(model);
Model
public partial class Customer
public Guid CustomerId get; set;
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CustId get; set;
[Required]
[StringLength(50)]
public string FirstName get; set;
[Required]
[StringLength(50)]
public string LastName get; set;
[Required]
[StringLength(254)]
public string EmailId get; set;
[Required]
[StringLength(100)]
public string PhoneNumber get; set;
public DateTime? CreatedDate get; set;
[Required]
public string Password get; set;
[Required]
public string ConfirmPassword get; set;
public bool IsEmailVerified get; set;
public Guid ActivationCode get; set;
[StringLength(100)]
public string ResetPasswordCode get; set;
【问题讨论】:
你想要角色在哪里?你想创建角色还是需要属性让控制器在特定角色上执行? ASP.NET Identity 的脚手架会自动在您的数据库上创建表,因为它是代码优先的方法。如果你去你的数据库,那么如果我没记错的话,你会发现 AspNetUsers 和 AspNetRoles 表。您可以在该表中设置您的角色。如果您不想使用这些表,那么您可以创建自己的授权过滤器属性。 【参考方案1】:当然,您应该需要使用 RoleManager 类的实例,这将为用户创建、检查和分配角色提供便利。
private ApplicationRoleManager _roleManager;
public ApplicationRoleManager RoleManager
get
return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
private set
_roleManager = value;
当你想在表中注册新的用户时,将以下代码放入注册方法中。
if (!RoleManager.RoleExists("<roleName>"))
var role = new IdentityRole("<roleName>");
var roleresult = await RoleManager.CreateAsync(role);
if (!roleresult.Succeeded)
ModelState.AddModelError("", roleresult.Errors.First());
return View(model);
【讨论】:
以上是关于如何使用 asp.net mvc 从头开始添加用户角色的主要内容,如果未能解决你的问题,请参考以下文章
如何设置一个简单的ASP.NET MVC C#项目? [关闭]
Visual Studio 2017 ASP.NET MVC 核心模板中的 Bower 替换