我在Microsoft sql server express中创建了一个数据库。我需要能够使用我的数据库登录Mvc 2应用程序(不是AcountController上现有的数据库,意味着MembershipService)
我只需要用我的数据库替换MemeberAhipService。我该怎么做(我首先使用实体框架代码)。我不需要在visual studio中创建模型。我有usermodel,userContext:Db。我想我也需要存储库。谁能告诉我一个例子,告诉我步骤?
答案 0 :(得分:1)
您可以创建自己的MembershipService。
示例:
新的MembershipService.cs(或任何你想要的)
public class MembershipService { public bool IsUserValid(string username, string password) { var db = new DatabaseContext(); var user = db.GetUser(username, password); // Or however you want to get your data, via Context or Repository return (user != null); } }
新FormsClass.cs
public class FormService { public void SignIn(string username, List<string> roles) { FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, // Version username, // Username DateTime.Now, // Creation DateTime.Now.AddMinutes(30), // Expiration false, // Persistent string.Join(",", roles.ToArray())); // Roles string encTicket = FormsAuthentication.Encrypt(authTicket); HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); GenericIdentity id = new GenericIdentity(username); HttpContext.Current.User = new GenericPrincipal(id, roles.ToArray()); } }
在Global.asax中:
protected void Application_PostAuthenticateRequest(object sender, EventArgs e) { HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { string encTicket = authCookie.Value; if (!String.IsNullOrEmpty(encTicket)) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(encTicket); FormsIdentity id = (FormsIdentity)Context.User.Identity; var roles = ticket.UserData.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); GenericPrincipal prin = new GenericPrincipal(id, roles); HttpContext.Current.User = prin; } } }