【问题标题】:ViewBag is not sending any value to the viewViewBag 没有向视图发送任何值
【发布时间】:2020-09-14 08:11:03
【问题描述】:

在 ASP.NET Core MVC 中,我在创建登录面板时遇到了麻烦,我在用户登录帐户后使用会话并将会话值存储在 ViewBag 中。但是 ViewBag 在里面没有得到任何值,而是在里面得到了 null 值。

这是控制器

[HttpPost]
        public IActionResult Login(userModel model)
        {
            var findValue = _context.users.Any(o => o.username == model.username);
            var findValue2 = _context.users.Any(o => o.password == model.password);
            if (findValue && findValue2)
            {
                HttpContext.Session.SetString("Username", model.username);
            }
            return View(model);
        }

public IActionResult Index()
        {
            ViewBag.Username = HttpContext.Session.GetString("Username");
            return View();
        }

这是视图 索引.cshtml

@model ComplaintManagement.Models.userModel
@{
    ViewData["Title"] = "Portal";
}

<h1>Welcome @ViewBag.Username</h1>

登录.cshtml

@model ComplaintManagement.Models.userModel
@{
    ViewData["Title"] = "Login";
}
<div class="row mb-3">
    <div class="col-lg-4"></div>

    <div class="col-lg-4 border login" style="background-color: #d3d1d1;">
        <h4 class="mt-3 text-center">
            <i class="fa fa-lg fa-user text-secondary"></i><br />
            Login
        </h4>
        <hr />
        <form method="post" asp-action="Index" asp-controller="Portal">
            <div class="text-danger"></div>
            <div class="text-warning">@ViewBag.Name</div>
            <div class="form-group">
                <label class="mt-4 asp-for=" username"">Username</label>
                <input class="form-control" type="text" required="required" asp-for="username" />
                <span></span>
            </div>

            <div class="form-group">
                <label class="mt-4" asp-for="password">Password</label>
                <input type="password" class="form-control" required="required" asp-for="password" />
                <span></span>
            </div>

            <center>Don't have an account? <a asp-controller="Portal" asp-action="Register">Register here</a>.</center>
            <center><button value="login" class="btn btn-primary mt-3 w-25 mb-3 align-content-center">Login</button></center>
        </form>
    </div>
    <div class="col-lg-4"></div>
</div>

【问题讨论】:

  • var findValue = _context.users.Any(o =&gt; o.username == model.username); var findValue2 = _context.users.Any(o =&gt; o.password == model.password); 看起来无法正常工作。第一个查询将找到具有给定用户名的任何用户。第二个将找到具有给定密码的任何用户。不能保证两个查询都能找到相同的用户。你需要重新思考逻辑。 (此外,以纯文本形式存储密码也是一个很大的安全错误)。
  • 但是……你为什么还要尝试构建自己的登录系统呢? ASP.NET 带有它的身份特性,它将立即为您的应用程序添加现成的、安全的登录功能。它已经解决了尝试构建登录系统时可能发生的所有错误和安全问题(例如我提到的那个),包括您可能还没有想到的更多问题,并且具有它需要的功能你创造了很久。如果您需要,它也可以自定义。几乎没有理由不使用它。
  • 你能分享你的 Startup.cs 文件吗?或者你可以参考这个话题:docs.microsoft.com/en-us/aspnet/core/fundamentals/…。因为我有一种预感,你没有配置为使用 Session

标签: c# asp.net-core model-view-controller


【解决方案1】:

ASP.NET Core 中的会话和状态管理

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-3.1


这是一个演示如何在 ASP.NET Core 中使用 Session。

1.启动配置代码

ConfigureServices 中的AddSession,Configure 中的UseSession

 public class Startup
 {

    public void ConfigureServices(IServiceCollection services)
     {
        ...
        services.AddSession();
        ...
     }
     
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseSession();

        app.UseStaticFiles();

        ....
    }

2。控制器代码

public class AccountController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public IActionResult Login()
    {
        return View();
    }

    [HttpPost]
    public IActionResult Login(userModel model)
    {    
        if (string.IsNullOrEmpty(model.username
            ) || string.IsNullOrEmpty(model.password))
        {
            return NotFound();
        }

       //var user = await _context.users.FirstOrDefaultAsync(x => x.username == model.username && x.password == model.password);

        //if (user != null)
        if (model.username.Equals("test") && model.password.Equals("123"))
        {
            HttpContext.Session.SetString("username", model.username);
        }
        else
            ViewBag.error = "Invalid Account";
         
        return View("Index");
    }

    [HttpGet]
    public IActionResult Logout()
    {
        HttpContext.Session.Remove("username");
        return RedirectToAction("Index");
    }
}

3.视图代码

   <h3>Login Page</h3>
    @ViewBag.error
    <form method="post" asp-controller="account" asp-action="login">
        <table border="0" cellpadding="2" cellspacing="2">
            <tr>
                <td>Username</td>
                <td><input type="text" name="username"></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" name="password"></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="submit" value="Login"></td>
            </tr>
        </table>
    </form>

4.成功返回View的代码

@using Microsoft.AspNetCore.Http;

<h3>Success Page</h3>
Welcome @Context.Session.GetString("username")
<br>
<a asp-controller="account" asp-action="logout">Logout</a>

测试结果

【讨论】:

  • @FahadAzeem,您的Viewbag 代码是正确的,我更新了有关如何使用会话进行登录操作的代码。你可以试试。
猜你喜欢
  • 1970-01-01
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 2021-07-29
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 2016-01-20
相关资源
最近更新 更多