4

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?

Wayne Brantley
  • 694
  • 6
  • 11

1 Answers1

8

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...      
    }
}
labilbe
  • 3,501
  • 2
  • 29
  • 34
paaschpa
  • 4,816
  • 11
  • 15
  • as System.Web.HttpRequestWrapper is what I needed – Facio Ratio Apr 16 '15 at 21:12
  • Maybe something like var httpWrapper = new HttpRequestWrapper(orignalRequest); . I don't think any instance of HttpRequestWrapper is available within an instance of a Service...could be wrong, though. – paaschpa Apr 21 '15 at 21:56
  • That probably works as well. Simply doing this worked for me though: var orignalRequest = this.Request.OriginalRequest as System.Web.HttpRequestWrapper – Facio Ratio Apr 21 '15 at 23:55