如何在ASP.Net MVC4中的cshtml文件中获取会话值

Vet*_*tri 3 asp.net-mvc-routing asp.net-session asp.net-mvc-4

请帮助我,值是存储在特定用户的会话中,当我从cshtml检索会话值时,它显示PC用户名而不是数据库中存在的特定用户名.请建议会话代码以显示特定的用户名.我在Cotrtoller中使用此代码.

{public ActionResult LogIn(Models.Tbl_Users user)
        {
            Session["Username"] = user.UserName;
            var sessionval = Session["Username"].ToString();
            if (!ModelState.IsValid)
            {
                if (Isvalid(user.UserName, user.UserPassword))
                {
                    FormsAuthentication.SetAuthCookie(user.UserName, false);

                    string status = Session["Username"].ToString();
                    if (status == "admin")
                    {
                        //  return RedirectToAction("adminpage", "UserLogIn");
                        return RedirectToAction("adminpage", "UserLogin");
                    }
                    else
                    {
                        return RedirectToAction("userpage", "UserLogIn");
 }                   }
Run Code Online (Sandbox Code Playgroud)

这是我的cshtml代码:

{
 @Html.AntiForgeryToken()
        @if (Request.IsAuthenticated)
        { 

        <strong>@Html.Encode(User.Identity.Name)</strong>

                @Html.ActionLink("Log Out","LogOut","UserLogIn")



        }
Run Code Online (Sandbox Code Playgroud)

}

Roh*_*han 14

我认为您可以直接使用会话变量

@HttpContext.Current.Session["Username"].ToString();
Run Code Online (Sandbox Code Playgroud)

  • 试试这个 `@Html.ActionLink(@HttpContext.Current.Session["Username"].ToString(), "NameOfHandlingFunction");` (2认同)