更新时间:2022-04-23 06:09:38
这样做的好处是它适用于每次调用.
创建一个实现 IClientMessageInspector的类>.在 BeforeSendRequest 方法中,将您的自定义标头添加到传出消息中.它可能看起来像这样:
Create a class that implements IClientMessageInspector. In the BeforeSendRequest method, add your custom header to the outgoing message. It might look something like this:
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
{
HttpRequestMessageProperty httpRequestMessage;
object httpRequestMessageObject;
if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
{
httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
if (string.IsNullOrEmpty(httpRequestMessage.Headers[USER_AGENT_HTTP_HEADER]))
{
httpRequestMessage.Headers[USER_AGENT_HTTP_HEADER] = this.m_userAgent;
}
}
else
{
httpRequestMessage = new HttpRequestMessageProperty();
httpRequestMessage.Headers.Add(USER_AGENT_HTTP_HEADER, this.m_userAgent);
request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
}
return null;
}
然后创建一个端点行为,将消息检查器应用于客户端运行时.您可以通过属性或使用行为扩展元素的配置来应用行为.
Then create an endpoint behavior that applies the message inspector to the client runtime. You can apply the behavior via an attribute or via configuration using a behavior extension element.
这是一个很棒的 示例 如何将 HTTP 用户代理标头添加到所有请求消息.我在我的一些客户中使用它.您还可以通过实现 IDispatchMessageInspector.
Here is a great example of how to add an HTTP user-agent header to all request messages. I am using this in a few of my clients. You can also do the same on the service side by implementing the IDispatchMessageInspector.
这是你的想法吗?
更新:我发现了这个列表 紧凑框架支持的 WCF 功能.我相信消息检查器被归类为通道可扩展性",根据这篇文章,它受到紧凑框架的支持.
Update: I found this list of WCF features that are supported by the compact framework. I believe message inspectors classified as 'Channel Extensibility' which, according to this post, are supported by the compact framework.