如何在 servicestack.net 中获取 HttpContext [英] How to get HttpContext in servicestack.net

查看:26
本文介绍了如何在 servicestack.net 中获取 HttpContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法切换到所有服务堆栈的新提供程序、身份验证等.因此,我正在运行一个混合方案并且效果很好.

I am unable to switch to all of service stack's new providers, authentication, etc. So, I am running a hybrid scenario and that works great.

为了让当前用户投入使用,我这样做:

To get the current user in service, I do this:

    private IPrincipal CurrentUser()
    {
        var context = HttpContext.Current;
        if (context != null)
        {
            var user = context.User;
            if (user != null)
            {
                if (!user.Identity.IsAuthenticated)
                    return null;
                return user;
            }
        }
        return null;
    }

是否有替代/更好的方法可以直接从服务中获取当前的 http 上下文?如果不需要,我宁愿不必使用 HttpContext.Current?

Is there an alternative/better way to get the current http context directly from a service? I would prefer to not have to use the HttpContext.Current if I do not have to?

推荐答案

这是另一种方式...它通过 ServiceStack 获取 OriginalRequest 这将是一个 ASP.NET 请求(虽然可以如果不在 ASP.NET 应用程序中使用,则为 HttpListener HttpRequest).不确定它是否更好,但您的服务代码中不再有 HttpContext.Current .

This is alternative way... It goes through ServiceStack to get the OriginalRequest which will be an ASP.NET request (though could be HttpListener HttpRequest if not used within ASP.NET application). Not sure if it's better but you no longer have HttpContext.Current within your Service code.

public class MyService : Service
{
    public object Get(MyRequest request)
    {
        var originalRequest = this.Request.OriginalRequest as System.Web.HttpRequest;
        var user = originalRequest.RequestContext.HttpContext.User;               
        // more code...      
    }
}

这篇关于如何在 servicestack.net 中获取 HttpContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆