在ASP.NET MVC C#中创建会话(如PHP会话)? [英] Creating sessions in ASP.NET MVC C# like PHP Session?

查看:55
本文介绍了在ASP.NET MVC C#中创建会话(如PHP会话)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP.NET MVC应用程序中从页面重定向到页面时遇到问题.

I am having a problem with redirecting from page to page in my ASP.NET MVC application.

当前,登录功能没有问题.登录后的预期输出是重定向到应用程序的主页.

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.

但是在销毁会话之后,请尝试将其放在应用程序主页的浏览器 https://localhost:44360/home/home 的地址栏中.即使没有登录帐户,它也会被重定向.此外,即使注销了帐户,如果单击浏览器的后退"按钮,也会显示主页,而不应该显示该页面.

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. 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.

在PHP中,登录后,将创建该会话,并且您只需要调用该会话来检查是否存在用户,如果没有,则它将把您重定向到"404错误页面未找到"或仅键入浏览器地址栏中的链接,并且没有创建任何会话,它还会将您重定向到错误页面.我想在我的ASP.NET MVC应用程序中实现这种会话,但是如何?

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. I want to implement this kind of session in my ASP.NET MVC application, but how?

这是我的代码:

LoginController.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

// 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();
    }
}

这是我在 Home.cshtml 中的home控制器内调用 Logout 函数的方式.

This is how I call the LogOut function inside the home controller in my Home.cshtml.

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

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

谢谢您!

推荐答案

php中的许多框架使用SESSOIN进行标识刷新会话,您将看到自动注销但是dotnet使用Cookie代替身份会话

many framework in php use SESSOIN for identity flush session and you will see automatic logout but dotnet use cookie instead session in identity

这篇关于在ASP.NET MVC C#中创建会话(如PHP会话)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆