简体   繁体   English

像 PHP Session 一样在 ASP.NET MVC C# 中创建会话?

[英]Creating sessions in ASP.NET MVC C# like PHP Session?

I am having a problem with redirecting from page to page in my ASP.NET MVC application.我在 ASP.NET MVC 应用程序中从页面重定向到页面时遇到问题。

Currently, login functionality does not have a problem.目前,登录功能没有问题。 The expected output after logging in was to redirect to the home page of the application.登录后的预期输出是重定向到应用程序的主页。

Inside the home page, there is a logout button to destroy the session that has been created after logging in and redirect to login page.在主页里面,有一个注销按钮,用于销毁登录后创建的会话并重定向到登录页面。

But after destroying the session, and try to put this on the address bar of the browser https://localhost:44360/home/home which is the home page of the application.但是销毁会话后,尝试将其放在浏览器的地址栏https://localhost:44360/home/home ,这是应用程序的主页。 It was redirected even though there is no account logged in. Also, even after logging out to an account, if you click the back button of the browser, the home page is shown that it shouldn't be.即使没有登录帐户,它也会被重定向。此外,即使在注销帐户后,如果您单击浏览器的后退按钮,主页仍会显示它不应该出现。

In PHP, after logging in, the session is created and you only need to call that Session to check if there is a user, if not, then it will redirect you to a 404 Error Page Not Found Or if you type only the link inside the address bar of the browser and there is no session created it will also redirect you to an error page.在 PHP 中,登录后,会话被创建,你只需要调用该会话来检查是否有用户,如果没有,那么它会将你重定向到 404 错误页面未找到或者如果你只输入里面的链接浏览器的地址栏,并且没有创建会话,它也会将您重定向到错误页面。 I want to implement this kind of session in my ASP.NET MVC application, but how?我想在我的 ASP.NET MVC 应用程序中实现这种会话,但是如何实现?

Here is my code:这是我的代码:

LoginController.cs登录控制器.cs

[HttpPost]
public ActionResult Login(LoginModel userInfo, FormCollection collection, string returnUrl)
{
    ILogicInterface<LogicalUserInput, LogicalSystemResult> iLogic = new UserLoginCheck();
    LogicalUserInput userInput = new LogicalUserInput();
    _ = new LogicalSystemResult();

    try
    {
        userInput[typeof(LoginModel).FullName] = userInfo;
        LogicalSystemResult systemResult = iLogic.DoProcess(userInput);
        bool userCheckExist = systemResult.ResultCode != LogicalSystemResult.RESULT_CODE_ERR_DATA_NOT_EXIST;

        if (userCheckExist)
        {
            UserLoginModel loginModel = systemResult[typeof(UserLoginModel).FullName] as UserLoginModel;
            Session["userInfo"] = loginModel;
            FormsAuthentication.SetAuthCookie(loginModel.email, true);

            if (!string.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                if (loginModel.AccountType == 0) 
                {
                     return RedirectToAction("Home", "Home");
                } 
                else 
                {
                     return RedirectToAction("Error", "Error");
                }                   
            }
        }
        else
        {
            TempData.Clear();
            TempData["Title"] = "Error!";
            TempData["Message"] = " Invalid Username Or Password.";
            return View();
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        return RedirectToAction("Error", "Error");
    }
}

HomeController.cs家庭控制器.cs

// GET: Home
[Authorize]
public ActionResult Home()
{
    if (Session["userInfo"] == null) 
    {
        return RedirectToAction("Error", "Error");
    } 
    else 
    {
        UserLoginModel userLoginModel = Session["userInfo"] as UserLoginModel;
        TempData["user"] = userLoginModel.lastName + ", " + userLoginModel.firstName + " " + userLoginModel.middleName;
        string cookieValue = GlobalFunctions.StringToBase64Encode(userLoginModel.email);
        HttpCookie newCookie = new HttpCookie(GlobalFunctions.StringToBase64Encode("userInformation"), cookieValue);
        newCookie.Expires = DateTime.Now.AddHours(1);
        Response.Cookies.Add(newCookie);

        return View();              
    }         
}

[Authorize]
[HttpPost]
public ActionResult LogOut() 
{
    try 
    {
        Session.Abandon();
        FormsAuthentication.SignOut();
                    
        Session["userInfo"] = null;
        return RedirectToAction("Login", "Login");
    } 
    catch (Exception ex) 
    {
        Console.WriteLine(ex.Message);
        return View();
    }
}

This is how I call the LogOut function inside the home controller in my Home.cshtml .这就是我所说的LogOut在我的家里控制器内部功能Home.cshtml

<script>
    $("#cmdLogOff").on("click", function () {
        $("#HomeView").submit();
    });
</script>

@using (Ajax.BeginForm("LogOut",
         null,
         new AjaxOptions
         {
         },
    new { id = "HomeView" }))
{
   
}

Thank you and Regards,谢谢和问候,

php 中的许多框架使用 SESSOIN 进行身份刷新会话,您将看到自动注销但 dotnet 使用 cookie 而不是身份会话

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM