updev
updev

Reputation: 633

Object reference not set to an instance of an object #2

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?

Upvotes: 1

Views: 1806

Answers (5)

jason
jason

Reputation: 241583

Well, it looks like this.loginModel is null (or, it could be something within the call to this.loginModel.Login).

I suspect the former because you have

public AccountController() { }

where you never set this.loginModel.

Additionally, in this constructor

public AccountController(LoginModel loginModel) {
    this.loginModel = loginModel;
}

you didn't check that loginModel is not null. I think you remove the parameterless constructor and you should add a contract

Contract.Requires(loginModel != null);

Upvotes: 1

Andras Zoltan
Andras Zoltan

Reputation: 42333

Surely it's because the loginModel is 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 the NullReferenceException.

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 null LoginModel being passed in that constructor and throw an exception (typically ArgumentNullException; 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 your ArgumentNullException - 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.

Upvotes: 2

Jonny Cundall
Jonny Cundall

Reputation: 2612

I'd guess loginModel is null. If the AccountController was instantiated with the parameterless constructor that will have caused this.

Upvotes: 1

Chris Shain
Chris Shain

Reputation: 51319

Put a debugger breakpoint on the line in question.

When the code stops there, are any of the variables null?

My guess is that this.loginModel is null there. You can't call instance methods on null instances.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499730

Well, you've got two cosntructor - one of them sets this.loginModel (although it doesn't check that it sets it to a non-null value); the other doesn't.

Which constructor is being called? If it's the parameterless one, then I'm not surprised you're getting that error. Do you need both constructors? Is this being instantiated by some DI framework?

Upvotes: 3

Related Questions