Asp.net Mvc authentication and asp. netmvc Authentication
1. Install the Microsoft. AspNet. Identity. Core Component and the Core component of Identity authentication.
Install Microsoft. AspNet. Identity. EntityFramework, and EF implements Identity authentication.
Install Microsoft. AspNet. Identity. OWIN, which is used to replace Froms authentication.
Install Microsoft. Owin. Host. SystemWeb 3.1.0 to run the OWIN on IIS.
2. Add the Identity EF context and configure the database connection string.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.Identity.EntityFramework;
namespace IdentityTest.Models
{
public class AppIdentityDbContext : IdentityDbContext<IdentityUser>
{
public AppIdentityDbContext() : base("DefaultConnection") {
}
}
}
3. enable migration on the package console using enable-migrations. update-database is used to update the database. The database generates five tables.
4. Add the registration function to enable the GET method.
[HttpGet]
public ActionResult Register(string UserName, string Password)
{
var user = new IdentityUser
{
UserName = UserName
};
using (var userManager = new UserManager<IdentityUser, string>
(new UserStore<IdentityUser>(new AppIdentityDbContext())))
{
var result = userManager.Create(user, Password);
if (result.Succeeded)
{
return Json(new { IsSuc = true, Message = "注册成功" },JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { IsSuc = false, Message = result.Errors.ToString() },JsonRequestBehavior.AllowGet);
}
}
}
When an error is reported when the application is started, add
<Add key = "owin: AutomaticAppStartup" value = "false"/>
Run it again and enter http: // localhost: 58009/Home/Register in the browser? UserName = admin & Password = 123456: Registration successful
Query the database. A newly registered user is added to the [dbo]. [AspNetUsers] table.