我有一个托管在Windows服务中的WCF服务.使用此服务的客户端每次调用服务方法时都必须传递一个标识符(因为该标识符对于被调用的方法应该做什么很重要).我认为以某种方式将此标识符放入WCF头信息是个好主意.
如果是个好主意,我该如何自动将标识符添加到标题信息中.换句话说,每当用户调用WCF方法时,标识符必须自动添加到标头中.
更新: 使用WCF服务的客户端是Windows应用程序和Windows Mobile应用程序(使用Compact Framework).
Mar*_*ood 181
这样做的好处是它适用于每次通话.
创建一个实现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;
}
Run Code Online (Sandbox Code Playgroud)
然后创建一个端点行为,将消息检查器应用于客户端运行时.您可以通过属性或使用行为扩展元素的配置来应用行为.
以下是如何将HTTP用户代理标头添加到所有请求消息的一个很好的示例.我在一些客户中使用它.您也可以通过实现IDispatchMessageInspector在服务端执行相同的操作.
这是你的想法吗?
更新: 我发现了紧凑框架支持的WCF功能列表.我相信消息检查员被归类为"渠道可扩展性",根据这篇文章,它受到紧凑框架的支持.
Agi*_*Jon 79
您可以使用以下命令将其添加到呼叫
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
}
Run Code Online (Sandbox Code Playgroud)
然后,服务器端你使用以下方法获取它:
MessageHeaders headers = OperationContext.Current.IncomingMessageHeaders;
string identity = headers.GetHeader<string>("Identity", "http://www.my-website.com");
Run Code Online (Sandbox Code Playgroud)
Nim*_*van 32
如果您只想为服务的所有请求添加相同的标头,您可以不使用任何编码!
只需在客户端配置文件的端点节点下添加头节点和必需的头
<client>
<endpoint address="http://localhost/..." >
<headers>
<HeaderName>Value</HeaderName>
</headers>
</endpoint>
Run Code Online (Sandbox Code Playgroud)
br3*_*3nt 19
如果您想以面向对象的方式向每个 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 ...
}
Run Code Online (Sandbox Code Playgroud)
正如 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 ...
}
Run Code Online (Sandbox Code Playgroud)
完成面向对象方法所需的最后一部分是创建 WCF 自动生成的客户端的子类(我使用 Microsoft 的WCF Web 服务参考指南来生成 WCF 客户端)。
就我而言,我需要将 API 密钥附加到x-api-keyHTML 标头。
子类执行以下操作:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
最后,使用您的客户端!
var apiKey = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
var client = new Client (apiKey);
var result = client.SomeRequest()
Run Code Online (Sandbox Code Playgroud)
生成的 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>
Run Code Online (Sandbox Code Playgroud)
Sli*_*SFT 14
这是另一个有用的解决方案,使用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...
}
Run Code Online (Sandbox Code Playgroud)
Ωme*_*Man 10
这类似于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();
Run Code Online (Sandbox Code Playgroud)
这对我有用,改编自《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)
{
}
}
Run Code Online (Sandbox Code Playgroud)
声明这些类后,您可以将新行为添加到 WCF 客户端,如下所示:
client.Endpoint.Behaviors.Add(new AddUserAgentEndpointBehavior());
Run Code Online (Sandbox Code Playgroud)
小智 5
var endpoint = new EndpointAddress(new Uri(RemoteAddress),
new[] { AddressHeader.CreateAddressHeader(
"APIKey",
"",
"bda11d91-7ade-4da1-855d-24adfe39d174")
});
Run Code Online (Sandbox Code Playgroud)
这对我有用
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
164188 次 |
| 最近记录: |