asp.net - ASP.NET REPLACING Request.IsAuthenticated with a bool is generate System.NullReferenceException: Object reference not set to an instance of an object
问题描述
错误:
我想替换Request.IsAuthenticated因为标准模板有不同的注册和登录方法。我想用bool替换,我也尝试过使用int,您将在下面的代码中看到。
这是我使用 bool Authenticated的AccountController.cs登录方法:
//GET: Account/LoginTurist (new)
[HttpGet]
[AllowAnonymous]
public ActionResult LoginTurist()
{
return View();
}
//POST: Account/LoginTurist (new)
[HttpPost]
[AllowAnonymous]
public ActionResult LoginTurist(LoginVM obj)
{
bool userExists = db.Users.Any(u => u.Username == obj.Username && u.Password == obj.Password);
var viewModel = new LoginVM { Authenticated = Request.IsAuthenticated };
//var viewModel = new LoginVM { Authenticated = 0 };
if (userExists)
{
Session["UseId"] = db.Users.Single(x => x.Username == obj.Username).Id;
viewModel.Authenticated = true;
//viewModel.Authenticated = 1;
return RedirectToAction("Experiences", "Home");
}
// in case of incorect email or password
ViewBag.LoginMessage = "Nume utilizator sau parola incorecte!";
return View(viewModel);
}
这是模型 LoginVM:
namespace TuristWithComments.ViewModels
{
public class LoginVM
{
[Required]
[Display(Name = "Nume Utilizator")]
public string Username { get; set; }
[Required, DataType(DataType.Password)]
[Display(Name = "Parola")]
public string Password { get; set; }
[Display(Name = "Recunoaste dispozitivul?")]
public bool RememberMe { get; set; }
public bool Authenticated { get; set; }
//public int Authenticated { get; set; }
}
}
这是视图,LoginPartial.cshtml,我试图像这样替换Request.IsAuthenticated:
@*@using Microsoft.AspNet.Identity*@
@*@if (Request.IsAuthenticated)*@
@model TuristWithComments.ViewModels.LoginVM
@if (Model.Authenticated)
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
<ul class="nav navbar-nav navbar-right">
<li>
@*@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })*@
</li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>
}
}
else
{
<ul class="nav navbar-nav navbar-right">
@*<li>@Html.ActionLink("Inregistrare", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>*@
@*<li>@Html.ActionLink("Autentificare", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>*@
<li>@Html.ActionLink("Inregistrare", "RegisterTurist", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Autentificare", "LoginTurist", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
}
我可以理解Model.Authenticated为空(见第一张图片),但我究竟在哪里可以解决这个问题?Request.IsAuthenticated从一开始就是假的,这就是程序在启动时运行的原因。如何修复模型不为空?
或者是否有更好的、不同的方式来改变导航栏,你会用另一种方式吗?
稍后编辑: 在线搜索更多答案后,我看到很多关于“Web.config”的提及,女巫我没有进行任何修改,看起来像这样:
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>
这可能是关键吗?也许我需要在这里修改一些东西?
后来编辑 2,在大卫的评论之后: LoginPartial 视图是 NavigationBar 的一部分,女巫在默认布局(或主布局,如果你愿意)中,所有页面都在其中呈现,理论上是运行项目时打开的第一件事,不?!这是布局页面:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
<!--Lightbox for popup images-->
<link href="~/Content/lightbox.css" rel="stylesheet" />
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink(" ", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Acasa", "Index", "Home")</li>
<li>@Html.ActionLink("Recomandarile noastre", "Recommendations", "Home")</li>
<li>@Html.ActionLink("Experientele utilizatorilor", "Experiences", "Home")</li>
<li>@Html.ActionLink("Fii spontan!", "Spontaneous", "Home")</li>
<li>@Html.ActionLink("Contacteaza-ne", "Contact", "Home")</li>
<li>@Html.ActionLink("Despre noi", "About", "Home")</li>
</ul>
@Html.Partial("_LoginPartial") // <-- here it is
</div>
</div>
</div>
<div style="padding: 7px">
<img src="~/Content/Images/_banner7.png" class="img-responsive" />
</div>
<div class="panel panel-body">
<div class="col-md-2">
<!--Partial view for the sidemenu-->
@Html.Partial("_SideMenu")
</div>
<div class="col-md-10">
<div>
@RenderBody()
</div>
</div>
</div>
@*<hr />*@
<div class="container body-content">
<footer>
<p>© @DateTime.Now.Year - TuristWithComments in Banat by Ionut Guruian</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", false)
<!--Lightbox for popup images-->
<script src="~/Scripts/lightbox-2.6.js"></script>
</body>
</html>
此外,该操作确实有一个 GET,我在第一个代码片段中也添加了它。
用户将其凭据用于登录的 LoginTurist.cshtml 就是这里:
@using TuristWithComments.Models
@model TuristWithComments.ViewModels.LoginVM
@*@model LoginViewModel*@
@{
ViewBag.Title = "Autentificare";
}
<h2>@ViewBag.Title.</h2>
<div class="row">
<div class="col-md-8">
<section id="loginForm">
@using (Html.BeginForm("LoginTurist", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<h4>Autentificare</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">
<div class="checkbox">
@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe)
</div>
</div>
</div>*@
<h5 class="text-danger" style="padding-left:20%">@ViewBag.LoginMessage</h5>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Autentificare" class="btn btn-success" />
</div>
</div>
<p>
@Html.ActionLink("Inregistrare cont nou", "RegisterTurist")
</p>
}
</section>
</div>
<div class="col-md-4">
<section id="socialLoginForm">
@Html.Partial("_ExternalLoginsListPartial", new ExternalLoginListViewModel { ReturnUrl = ViewBag.ReturnUrl })
</section>
</div>
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
解决方案
这似乎与Authenticated
财产没有任何关系。 Model
是null
。因为您没有为视图提供模型:
return View();
应该:
return View(viewModel);
推荐阅读
- c# - 设置画笔的颜色 alpha 和不透明度有什么区别吗?
- javascript - 嵌套查询结果 ES6
- swift - 这两种创建实例的方式有什么不同?
- hive - Apache sentry hive 授予插入权限,但它不起作用
- python - HiveContext 与火花 sql
- functional-programming - 有没有一种方法可以用 Ramda 覆盖对象中的道具名称?
- video-capture - 如何在 OpenCV 中获取相机设备名称?
- php - PHP - 将字符串转换为已经格式化为数组的数组
- android - 如何在 libgdx android 中拖动单个纹理
- javascript - 在 ReactJS 上意外使用“开放”无限制全局变量