ASP.NET Core MVC视图调用LoginModel遇空引用异常求助
ASP.NET Core MVC登录后Profile视图显示用户名报错问题
我在ASP.NET Core MVC项目中实现了登录功能,希望登录后能在Profile.cshtml视图中显示用户名,但调用模型时出现以下错误:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Microsoft.AspNetCore.Mvc.Razor.RazorPage.Model.get 返回 null。
相关代码
LoginModel.cs
namespace MVC_Catálogo_Imágenes.Models { public class LoginModel { [Required(ErrorMessage = "Campo obligatorio")] public string? User { get; set; } [Required(ErrorMessage = "Campo obligatorio")] public string? Password { get; set; } } }
控制器代码(Controller.cs)
public ActionResult Login() { return View(); } [HttpPost] public ActionResult Login(LoginModel l) { try { using (SqlConnection con = new(_contexto.Valor)) { using (SqlCommand cmd = new("sp_login", con)) { cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add("@Usuario", System.Data.SqlDbType.VarChar).Value = l.User; cmd.Parameters.Add("@Pass", System.Data.SqlDbType.VarChar).Value = l.Password; cmd.Parameters.Add("@Estado", System.Data.SqlDbType.Bit).Value = 1; con.Open(); object result = cmd.ExecuteScalar(); int count = result == null ? 0 : Convert.ToInt32(result); con.Close(); if (count > 0) { IsAuthenticated = true; return RedirectToAction("Index", "Home"); } else { ViewData["error"] = "Usuario y/o contraseña incorrectos"; return View(); } } } } catch (Exception) { ViewData["error2"] = "Ha habido un error al iniciar sesión"; return View(); } }
Profile.cshtml
@model LoginModel <h5>@Model.User</h5>
问题原因
Profile视图声明绑定LoginModel,但对应的控制器Action没有向视图传递该模型的实例,导致Model为null,访问@Model.User时触发空引用异常。另外,登录成功后重定向到Home/Index,原LoginModel的数据不会自动携带到Profile视图。
解决方案
方案1:使用Session存储用户名(简单快速)
在Program.cs中配置Session支持:
// 添加Session服务 builder.Services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(30); // 设置超时时间 options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); // 在UseRouting之后、UseAuthorization之前添加Session中间件 app.UseSession();修改登录成功的代码,将用户名存入Session:
if (count > 0) { IsAuthenticated = true; // 保存用户名到Session HttpContext.Session.SetString("CurrentUser", l.User); return RedirectToAction("Index", "Home"); }修改Profile.cshtml直接从Session获取用户名:
<h5>@HttpContext.Session.GetString("CurrentUser")</h5>
方案2:使用ASP.NET Core身份认证(推荐,符合规范)
在Program.cs中配置Cookie认证:
builder.Services.AddAuthentication("CookieAuth") .AddCookie("CookieAuth", options => { options.LoginPath = "/Account/Login"; // 设置登录页路径 options.ExpireTimeSpan = TimeSpan.FromMinutes(30); }); // 在UseSession之后添加认证中间件 app.UseAuthentication(); app.UseAuthorization();修改登录成功的代码,创建Claims并登录:
if (count > 0) { IsAuthenticated = true; // 创建用户声明 var claims = new List<Claim> { new Claim(ClaimTypes.Name, l.User) }; var identity = new ClaimsIdentity(claims, "CookieAuth"); var principal = new ClaimsPrincipal(identity); // 登录 HttpContext.SignInAsync("CookieAuth", principal); return RedirectToAction("Index", "Home"); }修改Profile.cshtml从User.Identity获取用户名:
<h5>@User.Identity.Name</h5>
方案3:向Profile视图传递模型实例
如果坚持使用模型传递,需要在Profile对应的控制器Action中构建并传递LoginModel:
public ActionResult Profile() { // 从Session或Claims获取用户名 var userName = HttpContext.Session.GetString("CurrentUser") ?? User.Identity.Name; var model = new LoginModel { User = userName }; return View(model); }
内容的提问来源于stack exchange,提问作者lmbdr
相关产品推荐
相关产品推荐

