繁体   English   中英

Web API没有会话 - 需要检查用户是否经过身份验证

[英]Web API has no session - need to check if user is authenticated

我正在创建我的第一个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为null,这是因为WebAPI使用的无状态模型。

如何使用Web API实现此目的? 如何检查和查询当前用户是否有效? 我的会话通常会保留一些项目,例如chaps名称,在布局屏幕上呈现 - 但看起来现在不可能。

建议的方法是使用无状态身份验证和授权令牌

多年以来,使用OWIN中间件配置WebAPI以集成OAuth2工作流非常容易。

了解如何遵循本教程

您在OAuth2中所谓的会话项目 ,您谈论的声明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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