Question

I am using websecurity login with mv3. I am stuck with this problem
The error faced by me is :- Object reference not set to an instance of an object.

     @Html.AntiForgeryToken()
Line 53:                                 <a href="javascript:document.getElementById('logoutForm').submit()" class="logout"></a>
Line 54:                             }
Line 55:                         </li>
Line 56:                     </ul>

Source File: d:\Warid\HrmsWaridNew\HrmsWaridNew\Views\Shared_Layout.cshtml Line: 54

the login controller code..

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (checkLogin(model.UserName))
        {
            if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                Session["UserID"] = WebSecurity.CurrentUserId.ToString();
                Session["UserName"] = WebSecurity.CurrentUserName.ToString();

                return RedirectToLocal(returnUrl);
            }
        }
        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return View(model);
    }

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            WebSecurity.Logout();
            System.Web.HttpContext.Current.Session.Clear();
            System.Web.HttpContext.Current.Session.Abandon();
            System.Web.HttpContext.Current.User = null;

            return RedirectToAction("Login", "Account");
        }
Was it helpful?

Solution

This is what i infer from the details you have provided. That there is a file in your project named as Shared_Layout.cshtml. In this file you have got an object on line 36,37,38 or 39 which you are trying to use without instantiating it first.

Now, how will you know what is null. It is very simple as well. Click on the line 36 and press F9. It will place a break point in your application. Now press F5 it will start the debug process. Now logoff and your debugger will stop at the line you placed the debugger. Now you can see what is null.

OTHER TIPS

The line in your question says:-

Object Reference not set to an instance NullReferenceException

Null reference exception occurs when we fail to initialize a reference type in our code, and try to use it afterwards.
foreg

   List<string> myList = null ; 
   myList.Add("Tom") ; // This will throw a null reference exception.

To correct it Properly initalize a reference type in C#

  List<string> myList = new List<string> () ; 
  myList.Add("Tom") // compiles and runs fine.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top