【问题标题】:How do I save a servicestack session in a method when not calling the method from an MVC context不从 MVC 上下文调用方法时,如何在方法中保存 servicestack 会话
【发布时间】:2015-10-28 11:32:23
【问题描述】:

我看过:https://github.com/ServiceStack/ServiceStack/wiki/Sessions#saving-outside-a-service

我仍然不明白,如果我有一个我想从 MVC 控制器和 servicestack 服务调用的类方法,我如何保存会话。是否可以不传递服务引用?...以下是我的用例:

    public async Task<User> StoreAsync(User user, CustomUserSession session)
    {
        using (var db = DbFactory.Open())
        {
            await db.SaveAsync(user).ConfigureAwait(false);
        }
        if (session != null)
        {
            session.EmailConfirmed = user.EmailConfirmed;
            session.ProfileImageUrl = user.ProfileImageUrl;
            session.ThumbnailProfileImageUrl = user.ThumbnailProfileImageUrl;

            //Following only works if I am calling the method from an MVC controller
            IHttpRequest httpReq = HttpContext.Current.ToRequest();
            httpReq.SaveSession(session);

            //What if I call this method from a servicestack service, 
            //I don't really want to inject the service as an optional parameter
        }
        return user;
    }

【问题讨论】:

    标签: asp.net-mvc session servicestack


    【解决方案1】:

    为了保存会话,您需要访问当前 HTTP 请求,以便访问附加到传入请求的用户 Permanent and Temporary Session Ids Cookie。

    Session Wiki 显示了在 ServiceStack 服务之外access the current IHttpRequest 的不同方式:

    IHttpRequest httpReq = aspCtx.ToRequest(); //HttpContext
    IHttpRequest httpReq = aspReq.ToRequest(); //MVC HttpRequestBase
    IHttpRequest httpReq = listenerCtx.ToRequest(); //HttpListenerContext
    
    //In ASP.NET hosts via the singleton
    IHttpRequest httpReq = HostContext.AppHost.TryGetCurrentRequest(); 
    

    一旦您可以访问当前的IRequest,您就可以使用SaveSession() 扩展方法保存您输入的会话:

    httpReq.SaveSession(session);
    

    您只能通过HttpContext.Current 单例在HTTP 请求的上下文中 访问当前请求,因此您需要确保HttpContext.Current 不为空。当通过 background thread 访问时,它将为 null,如果您的 async method 在后台线程上执行,而您需要解决 @987654329,这可能是您的问题@ 来自 HTTP Worker 线程。

    【讨论】:

    • 感谢您的快速答复!我会用 ConfigureAwait(true) 尝试几次;而不是 ConfigureAwait(false) 然后尝试为此删除异步。
    • 是的,只是 configureawait,我会先把它放在适当的位置,然后在稍后传递会话时不会想到它。
    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-16
    • 2017-06-21
    • 2016-10-05
    相关资源
    最近更新 更多