如何解决ASP.NET REPLACING Request.IsAuthenticated与bool是一般的System.NullReferenceException:对象引用未设置为对象的实例
错误:
我想替换 Request.IsAuthenticated ,因为我在标准模板中具有不同的注册和登录方法。我想用一个 bool 代替,我也尝试过用一个 int ,正如您在下面的代码中看到的那样。
这是我的 AccountController.cs 登录方法,我在其中使用bool Authenticated :
//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",htmlAttributes: new { id = "registerLink" })</li>*@
@*<li>@Html.ActionLink("Autentificare","Login",htmlAttributes: new { id = "loginLink" })</li>*@
<li>@Html.ActionLink("Inregistrare","RegisterTurist",htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Autentificare","LoginTurist",htmlAttributes: new { id = "loginLink" })</li>
</ul>
}
我可以理解 Model.Authenticated 为空(请参见第一张图片),但是我在哪里可以解决这个问题? Request.IsAuthenticated 开头为 false ,这就是程序在启动时运行的原因。 如何修复模型不为空?
或者也许有更好的,不同的方式来更改导航栏,您会以另一种方式来做吗?
以后的修改: 在网上搜索更多答案后,我看到很多关于“ Web.config”的提及,但我没有做任何修改,看起来像这样:
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>
这可能是关键吗?也许我需要在这里修改一些内容?
稍后编辑2 ,在David发表评论后: 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(" ","Home",new { area = "" },new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Acasa","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",new { ReturnUrl = ViewBag.ReturnUrl },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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。