我试图在asp.net中学习身份。我创建了一个非常简单的应用程序,但是我遇到了将测试用户设置为CreateIdentity的问题。
我创建了一个OwinStartup:
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security.Cookies;
[assembly: OwinStartup(typeof(Identity.Startup))]
namespace Identity
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Login")
});
}
}
}
我有一个简单的页面:
@using (Html.BeginForm("SignIn", "Login"))
{
<input type="text" name="user" placeholder="user" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Login" id="btnSubmit" />
}
然后,在我的控制器中,我尝试验证用户和密码(我的测试的硬代码)。
public ActionResult SignIn(UserModel model)
{
// just for test
string defaultPassword = "123456";
string defaultUser = "test";
if(model.User == defaultUser && model.Password == defaultPassword)
{
// Set authentication
var userStore = new UserStore<IdentityUser>();
var manager = new UserManager<IdentityUser>(userStore);
var authenticationManager = HttpContext.GetOwinContext().Authentication;
var userIdentity = manager.CreateIdentity(model, DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);
}
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
我的问题是manager.CreateIdentity
正在等待变量类型的IdentityUser,而不是我的模型。如何创建IdentityUser?
由于
答案 0 :(得分:0)
使用Create方法,然后将Identity模型映射到您的模型:
var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
ApplicationUserManager _userManager = new ApplicationUserManager(store);
var manager = _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
var appUser = new ApplicationUser() { UserName = user.UserEmail, PhoneNumber = user.UserPhone, Email = user.UserEmail, PasswordHash = manager.PasswordHasher.HashPassword(user.UserPassword) };
var createResult = manager.Create(appUser, appUser.PasswordHash);
if (createResult.Succeeded)
{
}