Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get HttpContext in servicestack.net

Tags:

servicestack

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?

like image 938
Wayne Brantley Avatar asked Feb 16 '23 11:02

Wayne Brantley


1 Answers

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...      
    }
}
like image 67
paaschpa Avatar answered Apr 21 '23 00:04

paaschpa