c# - 如何读取 HTTP header 值

标签 c# json wcf

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

在我的网络服务中,它是在服务中自托管的,并且一切运行良好,除了我想将安全 token 移动到请求的 header 中,以便类对象保持整洁。 (如果我无法将其放入标题中,我将求助于将其放入类中,但这在我看来有点难看)。

我已经查看了这个http://msdn.microsoft.com/en-us/library/system.servicemodel.operationcontext.incomingmessageheaders.aspx#Y342中的代码我似乎无法枚举 header 值。

查看 Fiddler,我可以看到 header 正在传递

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 配置,或者是否没有实现必要的接口(interface)。

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
});

最后在我的服务实现中的 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 无法看到 header 。

最佳答案

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

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

关于c# - 如何读取 HTTP header 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12574734/

相关文章:

wcf - 更改 WCF 基址

c# - 如果凭据错误,我可以禁用 MS CRM 2011 SDK 的登录提示吗?

c# - 如何在 NEST 中附加两个 SearchDescriptors

C# metro - 后台任务刷新不到 15 分钟

javascript - JS : merging 2 arrays within an object

javascript - Angular $resource JSON 回调不起作用——这是最佳实践吗?

winforms - 如何使用 NTLM 授权方案调用 Web 服务?

c# - 从类型名称动态创建委托(delegate)

c# - 从 C# 针对 ADAM 验证 ADAM 用户 - 无法绑定(bind)

json - 运行脚本时数据不刷新(NodeJs Lambda Alexa Skill)