C# 获取用户';asp.net mvc中的会话ID
在asp.net mvc应用程序中,我希望使用rest Web服务返回与作为参数传递的会话id关联的用户名 如何获取登录用户的sessionID 我是否需要在登录方法中手动设置会话ID 另外,如何使用会话ID获取用户信息 任何帮助都将不胜感激。谢谢大家! 帐户控制器中的登录方法:C# 获取用户';asp.net mvc中的会话ID,c#,asp.net,asp.net-mvc,session,C#,Asp.net,Asp.net Mvc,Session,在asp.net mvc应用程序中,我希望使用rest Web服务返回与作为参数传递的会话id关联的用户名 如何获取登录用户的sessionID 我是否需要在登录方法中手动设置会话ID 另外,如何使用会话ID获取用户信息 任何帮助都将不胜感激。谢谢大家! 帐户控制器中的登录方法: [HttpPost] public ActionResult LogIn(UserLoginView ULV, string returnUrl) { if (ModelState.Is
[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();
}
public class UserController : ApiController
{
[HttpGet]
public string UserInfo()
{
HttpSessionState sessionValue = HttpContext.Current.Session;
return sessionValue.SessionID.ToString();
}
}
用户控制器中的Web服务方法:
[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();
}
public class UserController : ApiController
{
[HttpGet]
public string UserInfo()
{
HttpSessionState sessionValue = HttpContext.Current.Session;
return sessionValue.SessionID.ToString();
}
}
您使用的是什么版本的.NET?使用.NETFramework4.5.2,我能够通过以下方式获得SessionID值:
stringsessionID=HttpContext.Session.SessionID代码>此链接中的第一个答案提供了获取会话ID的解决方案。我使用的是相同的版本。我仍然在sessionID行上得到一个空引用异常。在WebAPI控制器方法中尝试从HttpContext.Current.Session
获取SessionID时,我还收到一个NullReferenceException,因为Session为NULL。在MVC页面控制器方法中不会发生这种情况。在MVC控制器方法中,HttpContext.Current似乎不存在。我必须在MVC控制器方法中使用HttpContext.Session
。我刚刚读了一篇文章,说WebAPI方法是无会话的。试着在下面的堆栈溢出帖子中阅读关于在WebAPI中启用会话的内容:我找到了解决方案。结果证明它是有用的!非常感谢您的时间和帮助@JohnYes。我刚刚确认该解决方案将解决您的问题。很酷。