本文介绍了将HTTP请求/响应标头从调用复制到HttpWebRequest吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#WCF服务,该服务接收请求消息并将其发布到另一个服务.通过HttpWebRequest完成发布到其他服务.当我将原始请求HTTP标头发布到其他服务时,如何将其放入原始服务请求HTTP标头并将其放入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.

类似这样的东西:

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

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

我知道这是行不通的,因为HttpWebRequest loHttp具有自己的属性,并且当我尝试以上述方式设置ContentType时,它会引发异常,因为需要这样设置:

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];

有没有办法从呼叫中复制HTTP请求标头,并将其作为HTTP请求标头放置到另一个HttpWebRequest中?另外,原始请求可能还设置了其他自定义标头,我也希望将其发送到其他服务.

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.

谢谢你,阿德里亚

推荐答案

您可以通过

OperationContext.Current.RequestContext.RequestMessage.Headers

您可以通过设置标题

WebClient.Headers

示例:

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:

  • 接受
  • 连接
  • 内容长度
  • 内容类型
  • 日期
  • 期望
  • 主机
  • 自修改以来
  • 范围
  • 推荐人
  • 传输编码
  • 用户代理
  • 代理连接

我想您应该逐案查看可以/希望将哪些标头从传入呼叫复制到传出呼叫.

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

这篇关于将HTTP请求/响应标头从调用复制到HttpWebRequest吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:50
查看更多