我正在从 mvc 3 切换到 mvc 5,我知道他们更改了 .Net 4.5.1 中的身份验证(OWIN 身份验证)。
我只需要它来登录网站,以便 Request.IsAuthenticated 为真,我不想要 Microsoft 的成员(member)资格,我想使用我的数据库。
我试过的连这个都不行
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "Name"));
claims.Add(new Claim(ClaimTypes.Email, "mail@mail.com"));
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
var ctx = HttpContext.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(identity);
我真的不知道该怎么做,但我想使用我自己的数据库登录系统,只有用户名和密码
最佳答案
试试这个,希望对你有帮助。
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = MyViewModels.checkUser(model.UserName, model.Password);
if (user!=null)
{
SignInAsync();
return RedirectToAction("Welcome");
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
return View(model);
}
private void SignInAsync()
{
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "UserName"));
claims.Add(new Claim(ClaimTypes.Email, "User@mail.com"));
var id = new ClaimsIdentity(claims,
DefaultAuthenticationTypes.ApplicationCookie);
var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(id);
}
[Authorize]
public ActionResult Welcome()
{
return View();
}
如果你在 Action 中添加[Authorize]属性,那么它只会重定向用户名和密码是授权
从数据库中获取用户名和密码的函数
public static UserTable checkUser(string userName, string password)
{
DemoEntities db = new DemoEntities();
var query = (from u in db.UserTables
where u.UserName == userName && u.Password == password
select u).FirstOrDefault();
if(query!=null)
return query;
else
return null;
}
关于c# - MVC 5 登录自定义数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21658725/