如何读取HTTP标头值

时间:2012-09-25 00:28:18

标签: c# json wcf

我有一个从Iphone应用程序调用的WebService(我也在构建)

在我的web服务中它是在服务中自我托管并且它一切运行良好,除了我想将安全令牌移动到请求的标头中以便类对象保持整洁。 (如果我不能在标题中得到它,我会把它放在课堂上,但这有点丑陋)。

我查看了此http://msdn.microsoft.com/en-us/library/system.servicemodel.operationcontext.incomingmessageheaders.aspx#Y342中的代码,似乎无法枚举标头值。

看着Fiddler,我可以看到标题正在传递

POST http://192.168.1.221:11001/StockControl/json/SubmitResults HTTP/1.1
Device-Token: bwI2YiAHR4q3Ba5JVj99Cw==
Content-Type: application/json
Content-Length: 1663
User-Agent: StockManage/1.0 CFNetwork/609 Darwin/12.1.0

我不确定我是否未正确设置SelfHosted配置,或者我是否未实现必要的界面。

WCF IClientMessageInspector and the incoming SOAP headers但这是使用SOAP而我正在使用JSON。

使用以下

设置我的端点
WebHttpBinding jsonBind = new WebHttpBinding();
ServiceEndpoint jsonServer = host.AddServiceEndpoint(typeof(POSServer.StockControl.IStockService), jsonBind, "json");

jsonServer.Behaviors.Add(new WebHttpBehavior
{
    DefaultBodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Bare,
    HelpEnabled = true,
    DefaultOutgoingResponseFormat = WebMessageFormat.Json
});

最后在我的Service实现中的SubmitResults函数中

public bool SubmitResults(Business.StockResultData theData)
{
    DateTime uploadTime = DateTime.Now;
    int index = OperationContext.Current.IncomingMessageHeaders.FindHeader("Device-Token", "");
    this.WriteHeaders(OperationContext.Current.IncomingMessageHeaders);
    this.WriteHeaders(OperationContext.Current.RequestContext.RequestMessage.Headers);

但索引始终为-1(未找到),并且WriteHeaders无法看到标题。

2 个答案:

答案 0 :(得分:3)

经过大量的搜索,我相信我在这里找到了答案。 (http://social.msdn.microsoft.com/Forums/pl-PL/wcf/thread/72ee44cc-58bb-45b2-aff7-49d9bbc8176e)

HttpRequestMessageProperty reqMsg = 
          OperationContext.Current.IncomingMessageProperties["httpRequest"] as 
          HttpRequestMessageProperty;

答案 1 :(得分:0)

这对我有用......其中apiKey是标题名称

>  var headers =OperationContext.Current.IncomingMessageProperties["httpRequest"];
            var apiToken = ((HttpRequestMessageProperty)headers).Headers["apiKey"];