【发布时间】:2016-11-19 09:22:39
【问题描述】:
我正在创建我的第一个 WebAPI 项目,并且遇到了我的第一个障碍。似乎因为 WebAPI 模型是无状态的,所以我没有可用的 Session。所以,我在登录时添加会话变量的尝试失败了。
public static void CreateSession(int userId, string firstName, string surname, int timezoneOffset, string timezoneName)
{
// Create the object.
var session = new SessionToken
{
FirstName = firstName,
Surname = surname,
TimezoneName = timezoneName,
TimezoneOffset = timezoneOffset,
UserID = userId
};
// Is there an existing session?
var existing = HttpContext.Current.Session[SESSIONNAME];
// If so, we need to kill it and refresh it. Not sure why we would have this case though.
if (existing != null)
HttpContext.Current.Session.Remove(SESSIONNAME);
// Create the session.
HttpContext.Current.Session.Add(SESSIONNAME, session);
}
Session 为空,这是因为 WebAPI 使用了无状态模型。
如何使用 Web API 实现这一点?我怎样才能检查和查询当前用户是否有效?我的会话通常会保存一些项目,例如章节名称,以在布局屏幕上呈现 - 但现在看来这是不可能的。
【问题讨论】:
-
另一种方式,如果您想更安全,请使用JWT 或自定义等身份验证令牌。
-
这似乎启用了会话。这是最佳实践(因为 web api 似乎专门摆脱了会话),还是这是一个合适的修复?我看到了这一点,但从未在选择“个人用户帐户”的情况下创建我的项目。 dotnetcurry.com/aspnet/1223/…
标签: c# asp.net-web-api