Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy HTTP request / response headers from a call to a HttpWebRequest?

I have a C# WCF service that receives a request Message and post it to another service. Posting to the other service is done through HttpWebRequest. How can i get in my service the original request HTTP headers and put them in the HttpWebRequest when i post them to the other service.

Something like this:

HttpRequestMessageProperty httpRequestProp = GetHttpRequestProp(requestMessage);
 HttpWebRequest loHttp = (HttpWebRequest)WebRequest.Create(uri);
  foreach (var item in httpRequestProp.Headers.AllKeys)
            {

                 loHttp.Headers.Add(item, httpRequestProp.Headers[item]);
            }

I know this doesn't work because HttpWebRequest loHttp has its own properties, and when i try to set ContentType for example in the above way it throws exception because it needs to be set like this:

loHttp.ContentType = httpRequestProp.Headers[HttpRequestHeader.ContentType];

So is there a way to copy the HTTP request headers from a call and put them as HTTP request headers to another HttpWebRequest ? Also the original request might have other custom headers set and i want send those also to the other service.

Thank you, Adrya

like image 576
Adrya Avatar asked Jun 27 '11 05:06

Adrya


1 Answers

You can get the headers via

OperationContext.Current.RequestContext.RequestMessage.Headers

You can set the headers via

WebClient.Headers

Example:

WebClient wc = new WebClient();
wc.Headers.Add("referer", "http://yourwebsite.com");
wc.Headers.Add("user-agent", "Mozilla/5.0");

However, understand that some headers are restricted, and cannot be modified freely. These are:

  • Accept
  • Connection
  • Content-Length
  • Content-Type
  • Date
  • Expect
  • Host
  • If-Modified-Since
  • Range
  • Referer
  • Transfer-Encoding
  • User-Agent
  • Proxy-Connection

I suppose you should look, case by case, which headers you can/want to replicate from the incoming call to the outgoing one.

like image 147
Roy Dictus Avatar answered Sep 29 '22 01:09

Roy Dictus