Reputation: 1242
I currently have a populated database, a .NET 1.1 website and the task of re-writing it in MVC 3. I've created the MVC project with Forms Authentication, connected my database to the project, but don't know the best way to gain access to the information within it.
I came across this link: http://msdn.microsoft.com/en-us/library/f1kyba5e(v=vs.100).aspx?ppud=4, but I'm not sure if this is what I'm looking for in this case.
My goal for today is to get the login page working, so that I can use the admin account to login and see the main page of the site. I'm still very much a rookie with MVC and tend to search too broadly for answers. Hopefully there is something obvious that I'm missing.
Upvotes: 1
Views: 400
Reputation: 1038780
You don't need to write a custom membership provider right away. You could do that at a later stage. If you just want to get your application working with the LogOn screen all you have to do is modify the LogOn method in the default AccountController:
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
and then all you need is to write a ValidateUser method that will query your database and verify if the user exists:
private bool ValidateUser(string username, string password)
{
// TODO: query your db here and verify if the account exists
}
Later on you could write a custom Membership provider to avoid mixing db access logic into your controllers and separate the concerns. Here's a nice videao about writing a custom membership provider: http://www.asp.net/web-forms/videos/how-do-i/how-do-i-create-a-custom-membership-provider
You don't need to override all the methods of the MembershipProvider class, only those that you use. In the beginning you could start by overriding only the ValidateUser method to allow for user authenticating in your website using your custom data tables:
public class MyMembershipProvider : MembershipProvider
{
public override bool ValidateUser(string username, string password)
{
// put your data access logic here
}
...
}
Upvotes: 3