简体   繁体   中英

Get user's session ID in asp.net mvc

In an asp.net mvc application, i would like to use a rest webservice to return the username associated with the session id passed as a parameter.

How do I get the sessionID of the logged in User ?

Do I need to set the session ID Manually in my login method ?

Also how can I get the user information using the session ID ?

Any help will be appreciated. Thank you !

Login Method in Account Controller:

[HttpPost]
    public ActionResult LogIn(UserLoginView ULV, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            UserManager UM = new UserManager();
            string password = UM.GetUserPassword(ULV.EmailID);

            if (string.IsNullOrEmpty(password))
                ModelState.AddModelError("", "*The Email-ID or Password provided is incorrect");
            else
            {
                if (ULV.Password.Equals(password))
                {
                    FormsAuthentication.SetAuthCookie(ULV.EmailID, false);
                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "*The Password provided is incorrect");
                }
            }
        }

        return View();
    }

Web service method in User Controller:

 public class UserController : ApiController
    {
    [HttpGet]
    public string UserInfo()
    {
       HttpSessionState sessionValue = HttpContext.Current.Session;

        return sessionValue.SessionID.ToString();

    }
}

What version of .NET are you using? Using .NET Framework 4.5.2 I was able to obtain the SessionID value using: string sessionID = HttpContext.Session.SessionID;

链接链接中的第一个答案提供了获取会话 ID 的解决方案。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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