36

I've got some RESTful services running in a pure WCF context (i.e. ASP.NET compatibility is not enabled, and thus there is no HttpContext.Current object available).

The URLs to the services are rewritten at the start of the request using an IHttpModule (which at that point does have an HttpContext and rewrites it using HttpContext.Current.RewritePath) to get rid of things like the .svc extension from the URL.

However, I need to access the original URL that was requested from within the WCF infrastructure. Is there an equivalent to HttpContext.Current.Request.RawUrl on the OperationContext or WebOperationContext classes anywhere? Using WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri returns the rewritten URL not the original one.

Greg Beech
  • 133,383
  • 43
  • 204
  • 250

3 Answers3

41

You can get the endpoint currently targeted and the Uri for it by doing:

OperationContext.Current.RequestContext.RequestMessage.Headers.To

which I think is the same thing as:

OperationContext.Current.IncomingMessageHeaders.To

This is a System.Uri object, and I believe you can just get the OriginalString or PathAndQuery, or whatever parts you want from it.

christophercotton
  • 5,829
  • 2
  • 34
  • 49
2

try something like this:

OperationContext.Current.Channel.LocalAddress.Uri.AbsoluteUri
Prahalad Gaggar
  • 11,389
  • 16
  • 53
  • 71
aditya potdar
  • 357
  • 3
  • 8
  • Good answer according to the title of question (saying with google search perspective) – Sami Jan 30 '14 at 10:29
  • i tried System.ServiceModel.Web.WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri, OperationContext.Current.RequestContext.RequestMessage.Headers.To, and OperationContext.Current.IncomingMessageHeaders.To, the only one that works is OperationContext.Current.Channel.LocalAddress.Uri – rob Jan 29 '15 at 14:08
1

I have found that using

OperationContext.Current.RequestContext.RequestMessage.Headers.To

works most of the time, but did not for my application. It is behind an NLB (Network Load Balancer), which causes it to lose the original input host name. But the input host is still in a header named "Host", which was surprisingly hard to get at. It is located at:

System.ServiceModel.Web.WebOperationContext.Current.IncomingRequest.Headers["Host"]

(the header objects at System.ServiceModel.OperationContext.Current.IncomingMessageHeaders did not truly have all the headers from the client)

Abacus
  • 2,041
  • 1
  • 18
  • 23
  • Good point. Also note this problem with `UserHostAddress`: http://stackoverflow.com/q/650357/266535 – styfle Aug 11 '16 at 17:39