查看记录的UserName时出现NullReferenceException

时间:2016-01-26 07:17:32

标签: c# cookies

我正在尝试创建一个简单的登录页面并使用SetAuthCookie存储记录的用户,但我收到错误NullReferenceException was unhandled by user code。我还是新手,所以我对Cookies Authenticating还不熟悉

我在此行中错误

<h1> @Model.UserName </h1>

这是我的代码:

HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using logUser.Functions;
using logUser.Models;

namespace logUser.Controllers
{
public class HomeController : Controller
{
    [Authorize]
    public ActionResult Index()
    {
        UserInfo employeeUser = new UserInfo();
        employeeUser.UserName = User.Identity.Name;
        return View();
    }

}
}

的LoginController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using logUser.Models;
using logUser.Functions;

namespace logUser.Controllers
{
public class LoginController : Controller
{
    // GET: Login
    public ActionResult Login()
    {
        return View();
    }

    [HttpPost]
    public ActionResult DoLogin(logUser.Models.UserInfo u)
    {
        Employee bal = new Employee();
        if (bal.IsValidUser(u))
        {
            FormsAuthentication.SetAuthCookie(u.UserName, true);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            return View("Login");
        }
    }
}
}

Login.cshtml

@model logUser.Models.UserInfo
@{
Layout = null;
}

<h2>Login</h2>

<div>

@using (Html.BeginForm("DoLogin", "Login", FormMethod.Post))
{

@Html.LabelFor(c => c.UserName)

@Html.TextBoxFor(x => x.UserName)



<br />

@Html.LabelFor(c => c.Password)

@Html.PasswordFor(x => x.Password)

<br />


<input type="submit" name="BtnSubmit" value="Login" />

}

</div>

Employee.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using logUser.Models;

namespace logUser.Functions
{
public class Employee
{
    public bool IsValidUser(UserInfo u)
    {
        if (u.UserName == "Admin" && u.Password == "Admin")
        {

            return true;
        }
        else
        {
            return false;
        }
    }
}
}

Index.cshtml

@using logUser.Models
@model UserInfo
@{ var myMessage = "Hello World"; }
<p> Hi!  @myMessage </p>
<h1> @Model.UserName </h1>

注意:我已经配置了Web.config

由于

0 个答案:

没有答案