C# 使用存储库模式LINQ查询登录页面。获取错误

C# 使用存储库模式LINQ查询登录页面。获取错误,c#,asp.net-mvc,repository,C#,Asp.net Mvc,Repository,我正在使用存储库模式。当我登录时,我得到错误信息: “对象引用未设置为对象的实例。” 一切都很完美,但我不知道为什么会出现这样的错误。谁能告诉我哪里错了。 LoginView模型和用户模型是相同的,我使用的是数据库优先的方法 登录页面 public ActionResult Login(LoginViewModel loginModel ) { try { if (!string.IsNullOr

我正在使用存储库模式。当我登录时,我得到错误信息:

“对象引用未设置为对象的实例。”

一切都很完美,但我不知道为什么会出现这样的错误。谁能告诉我哪里错了。 LoginView模型和用户模型是相同的,我使用的是数据库优先的方法

登录页面

  public ActionResult Login(LoginViewModel loginModel )
        {
            try
            {
                if (!string.IsNullOrEmpty(loginModel.Username) && !string.IsNullOrEmpty(loginModel.Password))
                {
                    var Username = loginModel.Username;
                    var Password = loginModel.Password;

                    var result = _IUserRepository.ValidUser(Username, Password);
                    if (result.id==0 || result.id < 0)
                    {
                        ViewBag.errormessage = "Enter Invalid Username and Password";

                    }
                    else
                    {
                        return RedirectToAction("Index");
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
            return View();
        }
IUserRepository

  public class UserRepository : IUserRepository
        {
            private dbContext _context;
            public UserRepository(dbContext context)
            {
                this._context = context;
            }
            public bool UpdatePassword(user user)
            {
                throw new NotImplementedException();
            }

            public user ValidUser(string username, string passWord)
            {
                try
                {
                    var validate = (from user in _context.users
                                    where user.Username == username && user.Password == passWord
                                    select user).SingleOrDefault();
                    return validate;
                }
                catch (Exception ex)
                {

                    throw ex;
                }
            }
        }
 public interface IUserRepository
    {
        user ValidUser(string username, string password);
        bool UpdatePassword(user user);

    }
LoginViewModel

 public class LoginViewModel
    {

        public int id { get; set; }

        [Required(ErrorMessage ="Username is Required")]
        public string Username { get; set; }
        [Required(ErrorMessage = "Password is Required")]
        public string Password { get; set; }
    }
@model RepositoryPattren.Models.LoginViewModel

@{
    ViewBag.Title = "Login";
}

<h2>Login</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>LoginViewModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
Login.chtml

 public class LoginViewModel
    {

        public int id { get; set; }

        [Required(ErrorMessage ="Username is Required")]
        public string Username { get; set; }
        [Required(ErrorMessage = "Password is Required")]
        public string Password { get; set; }
    }
@model RepositoryPattren.Models.LoginViewModel

@{
    ViewBag.Title = "Login";
}

<h2>Login</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>LoginViewModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@model repositorypatteren.Models.LoginViewModel
@{
ViewBag.Title=“登录”;
}
登录
@使用(Html.BeginForm())
{
@Html.AntiForgeryToken()
LoginView模型

@Html.ValidationSummary(true,“,new{@class=“text danger”}) @LabelFor(model=>model.Username,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.Username,new{htmlAttributes=new{@class=“form control”}) @Html.ValidationMessageFor(model=>model.Username,“,new{@class=“text danger”}) @LabelFor(model=>model.Password,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.Password,new{htmlAttributes=new{@class=“form control”}) @Html.ValidationMessageFor(model=>model.Password,“,new{@class=“text danger”}) } @ActionLink(“返回列表”、“索引”)
尝试在代码中检查以下情况: 1-检查以确保您收到的登录模型不为空 2-您是否已注册IUserRepository依赖项?如果未注册,则不会注入实例 3-您使用的是SingleOrDefault,如果条件不匹配,它将为默认值返回null,并且您没有检查null,因此请执行以下代码:

if (result!=null && result.id==0 || result.id < 0)
                    {
                        ViewBag.errormessage = "Enter Invalid Username and Password";

                    }
                    else
                    {
                        return RedirectToAction("Index");
                    }
if(result!=null&&result.id==0 | | result.id<0)
{
ViewBag.errormessage=“输入无效的用户名和密码”;
}
其他的
{
返回操作(“索引”);
}

您可以添加完整的堆栈跟踪,以便我们知道错误发生的位置吗?如果没有具体的堆栈跟踪,则无法定义代码上发生的情况。此行的可能重复项返回null:
\u IUserRepository.ValidUser(用户名、密码)。您是否可以尝试在此处添加
ToList
:\u context.users.ToList()中用户的
?和调试ValidUser方法。您将从
ValidUser
函数返回
SingleOrDefault
。如果它的用户无效,这将返回null,并且在
Login
方法中,您正在访问用户的id,而不检查null。我有一些注释说明为什么iuserRepository依赖项不起作用。谢谢你的赏光。