简体   繁体   English

对象引用未设置为对象#2的实例

[英]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)) 我在上面的代码中如果(!this.loginModel.LogIn(loginViewModel,ref displayFullName,ref token))出现错误

Can any one help with this to find what's wrong in this one? 任何人都可以帮忙找到这个错在哪里吗?

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); 好吧,您有两个this.loginModel其中之一设置this.loginModel (尽管它不会检查是否将其设置为非null值); 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? 这是由某些DI框架实例化的吗?

Surely it's because the loginModel is supposed to be set in the constructor; 当然是因为应该在构造函数中设置loginModel but MVC will not fire the constructor that sets it; 但是MVC不会触发设置它的构造函数; it'll be firing the default constructor - so by that point it's null; 它会触发默认的构造函数-到那时它为null; hence the NullReferenceException . 因此NullReferenceException

I'm going to take a guess that you've inherited this Controller from someone else; 我猜你是从其他人那里继承了这个Controller的。 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). 除非像Jon提到的那样,否则站点上有一些DI框架处于活动状态(在这种情况下,其配置有误)。

If there's a DI framework creating the controller - then check that it can resolve an instance of LoginModel . 如果有一个DI框架正在创建控制器,则检查它是否可以解析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. 一种简单且实用的方法是,检查在该构造函数中传递的null LoginModel并引发异常(通常是ArgumentNullException ;使用另一个此处提到的代码约定是一个好计划),然后再次运行该站点。 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. 您可能会收到相同的错误(在这种情况下,可能不涉及DI),或者您将收到ArgumentNullException在这种情况下,并且配置错误。

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. 如果没有,则需要修改控制器的默认构造函数以创建LoginModel的默认实例-假定它的根位于Database或类似的东西中-最终,您需要查看项目的其余代码找出那个。

Well, it looks like this.loginModel is null (or, it could be something within the call to this.loginModel.Login ). 好吧,看起来this.loginModel为null(或者可能是在this.loginModel.Login调用中)。

I suspect the former because you have 我怀疑前者,因为你有

public AccountController() { }

where you never set this.loginModel . 您从未设置过this.loginModel

Additionally, in this constructor 此外,在此构造函数中

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

you didn't check that loginModel is not null . 您没有检查loginModel不为null I think you remove the parameterless constructor and you should add a contract 我认为您删除了无参数构造函数,应该添加一个合同

Contract.Requires(loginModel != null);

Put a debugger breakpoint on the line in question. 将调试器断点放在有问题的行上。

When the code stops there, are any of the variables null? 当代码在此处停止时,是否有任何变量为null?

My guess is that this.loginModel is null there. 我的猜测是this.loginModel为null。 You can't call instance methods on null instances. 您不能在空实例上调用实例方法。

I'd guess loginModel is null. 我猜loginModel为null。 If the AccountController was instantiated with the parameterless constructor that will have caused this. 如果AccountController是用将导致此问题的无参数构造函数实例化的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM