Anuja Sawant
Anuja Sawant

Reputation: 75

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

    }
}

Upvotes: 3

Views: 41418

Answers (2)

Anuja Sawant
Anuja Sawant

Reputation: 75

link The first answer in this link gives the solution to obtain the session ID.

Upvotes: 1

John Verco
John Verco

Reputation: 1377

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;

Upvotes: 7

Related Questions