我有一个托管在Windows服务中的WCF服务。使用此服务的客户端每次调用服务方法时都必须传递一个标识符(因为该标识符对于被调用的方法应该做什么很重要)。我认为以某种方式将此标识符放入WCF标头信息是个好主意。
如果是个好主意,我该如何自动将标识符添加到标题信息中。换句话说,每当用户调用WCF方法时,标识符必须自动添加到标题中。
更新 使用WCF服务的客户端既是Windows应用程序又是Windows Mobile应用程序(使用Compact Framework)。
答案 0 :(得分:169)
这样做的好处是它适用于每次通话。
创建一个实现IClientMessageInspector的类。在BeforeSendRequest方法中,将自定义标头添加到外发邮件中。它可能看起来像这样:
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;
}
然后创建将消息检查器应用于客户端运行时的端点行为。您可以通过属性或使用行为扩展元素的配置来应用行为。
这是一个很好的example如何向所有请求消息添加HTTP用户代理标头。我在一些客户中使用它。您也可以通过实施IDispatchMessageInspector。
在服务端执行相同操作这是你的想法吗?
更新:我发现了紧凑框架支持的list WCF功能。我相信消息检查员被归类为“渠道可扩展性”,根据这篇文章, 得到了紧凑框架的支持。
答案 1 :(得分:78)
您可以使用以下方法将其添加到通话中:
using (OperationContextScope scope = new OperationContextScope((IContextChannel)channel))
{
MessageHeader<string> header = new MessageHeader<string>("secret message");
var untyped = header.GetUntypedHeader("Identity", "http://www.my-website.com");
OperationContext.Current.OutgoingMessageHeaders.Add(untyped);
// now make the WCF call within this using block
}
然后,服务器端你使用:
抓住它MessageHeaders headers = OperationContext.Current.IncomingMessageHeaders;
string identity = headers.GetHeader<string>("Identity", "http://www.my-website.com");
答案 2 :(得分:33)
如果您只想为服务的所有请求添加相同的标题,您可以不进行任何编码!
只需在客户端配置文件
<client>
<endpoint address="http://localhost/..." >
<headers>
<HeaderName>Value</HeaderName>
</headers>
</endpoint>
答案 3 :(得分:12)
以下是使用ChannelFactory
作为代理手动将自定义HTTP标头添加到客户端WCF请求的另一个有用的解决方案。必须为每个请求执行此操作,但如果您只需要对代理进行单元测试以准备非.NET平台,则可以作为简单演示。
// create channel factory / proxy ...
using (OperationContextScope scope = new OperationContextScope(proxy))
{
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = new HttpRequestMessageProperty()
{
Headers =
{
{ "MyCustomHeader", Environment.UserName },
{ HttpRequestHeader.UserAgent, "My Custom Agent"}
}
};
// perform proxy operations...
}
答案 4 :(得分:8)
这类似于NimsDotNet的答案,但展示了如何以编程方式进行。
只需将标题添加到绑定
即可var cl = new MyServiceClient();
var eab = new EndpointAddressBuilder(cl.Endpoint.Address);
eab.Headers.Add( AddressHeader.CreateAddressHeader("ClientIdentification", // Header Name
string.Empty, // Namespace
"JabberwockyClient")); // Header Value
cl.Endpoint.Address = eab.ToEndpointAddress();
答案 5 :(得分:5)
var endpoint = new EndpointAddress(new Uri(RemoteAddress),
new[]
{
AddressHeader.CreateAddressHeader("APIKey", "",
"bda11d91-7ade-4da1-855d-24adfe39d174")
});
答案 6 :(得分:3)
您可以在MessageContract中指定自定义标题。
您还可以使用存储在配置文件中的< endpoint> headers,并将其全部复制到客户端/服务发送的所有邮件的标头中。这对于轻松添加一些静态标头很有用。
答案 7 :(得分:3)
这对我有用
TestService.ReconstitutionClient _serv = new TestService.TestClient();
using (OperationContextScope contextScope = new OperationContextScope(_serv.InnerChannel))
{
HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
requestMessage.Headers["apiKey"] = ConfigurationManager.AppSettings["apikey"];
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
_serv.Method(Testarg);
}
答案 8 :(得分:2)
.NET 3.5中的上下文bindings可能就是您正在寻找的内容。有三个开箱即用:BasicHttpContextBinding,NetTcpContextBinding和WSHttpContextBinding。上下文协议基本上传递消息头中的键值对。查看MSDN杂志上的Managing State With Durable Services文章。
答案 9 :(得分:2)
如果我理解你的要求,那么简单的答案就是:你做不到。
这是因为WCF服务的客户端可能由使用您服务的任何第三方生成。
IF 您可以控制服务的客户端,您可以创建一个基本客户端类,添加所需的标头并继承工作类的行为。
答案 10 :(得分:1)
这对我有用,改编自Adding HTTP Headers to WCF Calls
// Message inspector used to add the User-Agent HTTP Header to the WCF calls for Server
public class AddUserAgentClientMessageInspector : IClientMessageInspector
{
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel)
{
HttpRequestMessageProperty property = new HttpRequestMessageProperty();
var userAgent = "MyUserAgent/1.0.0.0";
if (request.Properties.Count == 0 || request.Properties[HttpRequestMessageProperty.Name] == null)
{
var property = new HttpRequestMessageProperty();
property.Headers["User-Agent"] = userAgent;
request.Properties.Add(HttpRequestMessageProperty.Name, property);
}
else
{
((HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name]).Headers["User-Agent"] = userAgent;
}
return null;
}
public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
}
}
// Endpoint behavior used to add the User-Agent HTTP Header to WCF calls for Server
public class AddUserAgentEndpointBehavior : IEndpointBehavior
{
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(new AddUserAgentClientMessageInspector());
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
}
public void Validate(ServiceEndpoint endpoint)
{
}
}
在声明这些类之后,您可以将新行为添加到WCF客户端,如下所示:
client.Endpoint.Behaviors.Add(new AddUserAgentEndpointBehavior());
答案 11 :(得分:0)
如果您想以面向对象的方式向每个WCF调用中添加自定义HTTP标头,那就别无所求。
就像Mark Good和paulwhit的回答一样,我们需要继承IClientMessageInspector
子类,以将自定义HTTP标头注入WCF请求。但是,通过接受包含我们要添加的标头的字典,让检查器更通用:
public class HttpHeaderMessageInspector : IClientMessageInspector
{
private Dictionary<string, string> Headers;
public HttpHeaderMessageInspector(Dictionary<string, string> headers)
{
Headers = headers;
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
// ensure the request header collection exists
if (request.Properties.Count == 0 || request.Properties[HttpRequestMessageProperty.Name] == null)
{
request.Properties.Add(HttpRequestMessageProperty.Name, new HttpRequestMessageProperty());
}
// get the request header collection from the request
var HeadersCollection = ((HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name]).Headers;
// add our headers
foreach (var header in Headers) HeadersCollection[header.Key] = header.Value;
return null;
}
// ... other unused interface methods removed for brevity ...
}
就像Mark Good和paulwhit的回答一样,我们需要将IEndpointBehavior
子类化,将HttpHeaderMessageInspector
注入到WCF客户中。
public class AddHttpHeaderMessageEndpointBehavior : IEndpointBehavior
{
private IClientMessageInspector HttpHeaderMessageInspector;
public AddHttpHeaderMessageEndpointBehavior(Dictionary<string, string> headers)
{
HttpHeaderMessageInspector = new HttpHeaderMessageInspector(headers);
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.ClientMessageInspectors.Add(HttpHeaderMessageInspector);
}
// ... other unused interface methods removed for brevity ...
}
完成面向对象方法的最后一部分是创建WCF自动生成的客户端的子类(我使用Microsoft的WCF Web Service Reference Guide生成WCF客户端)。
就我而言,我需要将API密钥附加到x-api-key
HTML标头中。
子类执行以下操作:
EndpointConfiguration
枚举,以传递给构造函数-也许您的实现中没有这个)AddHttpHeaderMessageEndpointBehavior
附加到客户的Endpoint
行为public class Client : MySoapClient
{
public Client(string apiKey) : base(EndpointConfiguration.SomeConfiguration)
{
var headers = new Dictionary<string, string>
{
["x-api-key"] = apiKey
};
var behaviour = new AddHttpHeaderMessageEndpointBehavior(headers);
Endpoint.EndpointBehaviors.Add(behaviour);
}
}
最后,使用您的客户端!
var apiKey = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
var client = new Client (apiKey);
var result = client.SomeRequest()
生成的HTTP请求应包含您的HTTP标头,如下所示:
POST http://localhost:8888/api/soap HTTP/1.1
Cache-Control: no-cache, max-age=0
Connection: Keep-Alive
Content-Type: text/xml; charset=utf-8
Accept-Encoding: gzip, deflate
x-api-key: XXXXXXXXXXXXXXXXXXXXXXXXX
SOAPAction: "http://localhost:8888/api/ISoapService/SomeRequest"
Content-Length: 144
Host: localhost:8888
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<SomeRequestxmlns="http://localhost:8888/api/"/>
</s:Body>
</s:Envelope>
答案 12 :(得分:0)
找到另一种方法here:
SoapServiceClient client = new SoapServiceClient();
using(new OperationContextScope(client.InnerChannel))
{
HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
requestMessage.Headers["MyHttpHeader"] = "MyHttpHeaderValue";
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
var result = client.MyClientMethod();
}
答案 13 :(得分:-1)
派对有点晚,但Juval Lowy在他的book和相关的ServiceModelEx图书馆中解决了这个问题。
基本上,他定义了允许指定类型安全标头值的ClientBase和ChannelFactory特化。我建议下载源代码并查看HeaderClientBase和HeaderChannelFactory类。
约翰