How to get HttpContext in servicestack.net

北城余情 提交于 2019-12-22 08:40:51

问题


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;
    }

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?


回答1:


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...      
    }
}


来源:https://stackoverflow.com/questions/16674263/how-to-get-httpcontext-in-servicestack-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!