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

China☆狼群 提交于 2021-02-08 15:35:00

问题


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


回答1:


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.




回答2:


For ex. you want to copy all Request headers to the HttpWebRequest headers:

HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
CopyHeaders(httpWebRequest, httpWebRequest.Headers, this.Request.Headers);

and implementation:

    void CopyHeaders(object rootTo, NameValueCollection to, NameValueCollection from)
    {
        foreach (string header in from.AllKeys)
        {
            try
            {
                to.Add(header, from[header]);
            }
            catch
            {
                try
                {
                    rootTo.GetType().GetProperty(header.Replace("-", "")).SetValue(rootTo, from[header]);
                }
                catch {}
            }
        }
    }

Hope it helps.



来源:https://stackoverflow.com/questions/6489057/copy-http-request-response-headers-from-a-call-to-a-httpwebrequest

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