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

时间:2019-12-07 15:05:50

标签: sql asp.net-core-mvc crud

我知道对此有答案,但是它们太混乱了,不能在代码中解决我的问题。我正在使用.net core 3.0创建一个租车网络应用程序。我正在尝试添加功能来租车,并且需要一种方法来生成某些字段的值。这是RentController:

protected int GetCurrentUserId()
    {
        ClaimsIdentity claimsIdentity = User.Identity as ClaimsIdentity;
        return int.Parse(claimsIdentity.Claims.Where(x => x.Type == ClaimTypes.NameIdentifier).FirstOrDefault().Value); //error
    }

    // GET: Rents/Create
    [HttpGet]
    public IActionResult Create(int id)
    {

        var brand = _context.Car.Single(c => c.CarId == id)?.Brand;
        return View(new Rent { CarId = id, Brand = brand, UserId = GetCurrentUserId(), 
            DateTaken = DateTime.Now, ReturnDate = DateTime.Now.AddMonths(1) });
    }

    // POST: Rents/Create

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("RentId,CarId,UserId,DateTaken,ReturnDate")] Rent rent)
    {
        if (ModelState.IsValid)
        {
            _context.Rent.Add(rent);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(rent);
    }

Rent.cs:

    public int Id { get; set; }
    public int CarId { get; set; }
    public int UserId { get; set; }
    public DateTime DateTaken { get; set; }
    public DateTime ReturnDate { get; set; }
    [NotMapped]
    public string Brand { get; set; }

Create.cshtml用于出租:

<form asp-action="Create">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="CarId" class="control-label"></label>
            <input asp-for="CarId" class="form-control" />
            <span asp-validation-for="CarId" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="UserId" class="control-label"></label>
            <input asp-for="UserId" class="form-control" />
            <span asp-validation-for="UserId" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="DateTaken" class="control-label"></label>
            <input asp-for="DateTaken" class="form-control" />
            <span asp-validation-for="DateTaken" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="ReturnDate" class="control-label"></label>
            <input asp-for="ReturnDate" class="form-control" />
            <span asp-validation-for="ReturnDate" class="text-danger"></span>
        </div>
        <div class="form-group">
            <input type="submit" value="Rent" class="btn btn-primary" />
        </div>
    </form>

LoginController:

[HttpGet]
    public IActionResult Login()
    {
        ViewData["HasError"] = false;
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Login(UserViewModel UserViewModel)
    {
        ViewData["HasError"] = true;

        User Model = new User();
        var MappedModel = Mapper.Map(UserViewModel, Model);
        var all = Repository.SelectAll().Result.ToList();
        //List<User> allof = all.Result.ToList();
        User user = null;
        userIdentity.AddClaim(new Claim("type", "value"));

        foreach (var item in all)
        {
            if (item.Email.Trim() == Model.Email && item.Password.Trim() == Model.Password)
            {
                user = item;
                HttpContext.Session.SetInt32(SessionUserId, user.UserId);
                HttpContext.Session.SetString(SessionFirstName, user.FirstName);
                HttpContext.Session.SetString(SessionLastName, user.LastName);
                HttpContext.Session.SetString(SessionDateOfBirth, user.DateOfBirth);
                HttpContext.Session.SetString(SessionGender, user.Gender);
                HttpContext.Session.SetString(SessionEmail, user.Email);
                HttpContext.Session.SetString(SessionUsername, user.Username);
                HttpContext.Session.SetString(SessionPassword, user.Password);
                HttpContext.Session.SetString(SessionIsLoggedIn, "true");
                if(item.Admin == true)
                {
                    HttpContext.Session.SetString(SessionIsAdmin, "true");
                    return RedirectToAction("AdminAccount");
                }
                else
                {
                    HttpContext.Session.SetString(SessionIsAdmin, "false");
                    return RedirectToAction("UserAccount");
                }
            }
        }
        return View();
    }

现在,我想为用户提供方便,这样他就不必输入自己的ID和所租车的ID。我已经搜索了很多次解决方案,但是它没有用,并且我没有足够的经验来理解和修复它。另外,我已经通过手动填写所有字段进行了检查,它可以正常工作,但其他用户仍然可以租用该车。我该怎么做才能防止这种情况? 预先感谢!

0 个答案:

没有答案