public class AccountController : Controller
{
private LoginModel loginModel = null;
#region Constructor
public AccountController(LoginModel loginModel)
{
this.loginModel = loginModel;
}
public AccountController()
{
}
#endregion
#region Login
//
// GET: /Account/Login
public ActionResult Login()
{
return View();
}
//
// POST: /Account/Login
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(string userName, string password, bool rememberMe, string returnUrl)
{
try
{
string displayFullName = null, token = null;
LoginViewModel loginViewModel = new LoginViewModel();
loginViewModel.UserName = userName;
loginViewModel.Password = password;
loginViewModel.RememberMe = rememberMe;
ModelState.AddModelErrors(loginViewModel.ValidateLogIn());
if (!ModelState.IsValid)
{
return View();
}
//login failed than return view.
if (!this.loginModel.LogIn(loginViewModel, ref displayFullName, ref token))
{
ModelState.AddModelError("_FORM", PortalErrors.IncorrectDataMsg);
return View();
}
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
catch (Exception exc)
{
ModelState.AddModelError("_FORM", PortalErrors.CommonErrMsg);
return View();
}
}
I get the error on my above code on line if (!this.loginModel.LogIn(loginViewModel, ref displayFullName, ref token))
Can any one help with this to find what’s wrong in this one?
Surely it’s because the
loginModelis supposed to be set in the constructor; but MVC will not fire the constructor that sets it; it’ll be firing the default constructor – so by that point it’s null; hence theNullReferenceException.I’m going to take a guess that you’ve inherited this Controller from someone else; and that they have written unit tests for it – hence the additional constructor; unless, as Jon has mentioned, there is some DI framework active on the site (in which case it’s misconfigured).
If there’s a DI framework creating the controller – then check that it can resolve an instance of
LoginModel. An easy way, and good practise, is to check for a nullLoginModelbeing passed in that constructor and throw an exception (typicallyArgumentNullException; the use of Code Contracts as mentioned by another answer here is a good plan) and then run the site again. Either you’ll get the same error (in which case there’s probably no DI involved), or you’ll get yourArgumentNullException– in which case there is and it’s badly configured.If there isn’t, you need to modify the default constructor of the controller to create the default instance of
LoginModel– presumably it has roots in a Database or something like that – ultimately you’ll need to look at the rest of the project’s code to figure that one out.