我刚刚开始使用ASP.Net MVC5
而我正面临一些挑战。
我有一个使用WebForms
的已构建系统,我正在将其迁移到MVC
。
我了解MVC
提供了Authentication
和Authorization
提供程序,但我希望基于我已有的数据库实现简单登录。
在我以前的系统中,当用户登录时,用户的id和角色存储在会话变量中并在所有页面中进行检查。该ID还用于应用程序中的某些任务。
有没有办法在现有数据库中使用MVC Identity Management
?
我在上一篇文章中尝试了以下内容,但似乎无法使其正常运行。
[HttpPost]
public ActionResult Login(string username, string password)
{
if (new UserManager.IsValid(username, password))
{
var ident = new ClaimsIdentity(
new[] {
// adding following 2 claim just for supporting default antiforgery provider
new Claim(ClaimTypes.NameIdentifier, username),
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
new Claim(ClaimTypes.Name,username),
// optionally you could add roles if any
new Claim(ClaimTypes.Role, "RoleName"),
new Claim(ClaimTypes.Role, "AnotherRole"),
},
DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.GetOwinContext().Authentication.SignIn(
new AuthenticationProperties { IsPersistent = false }, ident);
return RedirectToAction("MyAction"); // auth succeed
}
// invalid username or password
ModelState.AddModelError("", "invalid username or password");
return View();
}
class UserManager
{
public bool IsValid(string username, string password)
{
using(var db=new MyDbContext()) // use your DbConext
{
// if your users set name is Users
return db.Users.Any(u=>u.Username==username
&& u.Password==password);
}
}
}
请提供任何帮助和建议。