我在 Net 4.6 中使用 Windows 服务,我在 VS 2022 中创建了一个 WSDL 服务的服务引用,一切正常,但现在我必须在 HTTP 标头内容类型中添加一个参数。 问题是我使用的是 MTOM 传输,似乎我无法将任何内容附加到 Content-Type Header。 我试图在方法 BeforeSendRequest 中实现 CustomBehaviour 继承 IEndpointBehavior 和 IClientMessageInspector 的相关 CustomInspector 但似乎我无法读取其中的标头,因为 MTOM 消息在此调用后创建边界元素。
简而言之,我有这个 HTTP 标头 Content-Type
multipart/related;type="application/xop+xml";charset=UTF-8;start-info="application/soap+xml";boundary="uuid:00361b85-692d-43a1-9f17-57d70bbe26df+id= 1"
我必须像这样“附加”一些
action="{action}";
可能吗?
这是我的示例代码
WSHttpBinding wsHttpBinding = new WSHttpBinding();
wsHttpBinding.Security.Mode = SecurityMode.Transport;
wsHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
wsHttpBinding.MessageEncoding = WSMessageEncoding.Mtom;
Client = new ServiceClient(wsHttpBinding, new EndpointAddress(EndPoint));
这里我称我的自定义行为
Client.Endpoint.Behaviors.Add(new CustomBehavior(action));
然后我实施行为
public class CustomBehavior : IEndpointBehavior
{
private string action = null;
public CustomBehavior(string action, byte[] file)
{
this.action = action;
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { }
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { }
public void Validate(ServiceEndpoint endpoint) { }
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(new CustomInspector(this.action));
}
}
private class CustomInspector : IClientMessageInspector
{
private string action;
public CustomInspector(string action)
{
this.action = action;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
HttpRequestMessageProperty reqProps = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
if (reqProps != null)
{
reqProps = new HttpRequestMessageProperty();
}
reqProps.Headers.Add("Content-Type", $"multipart/related;type=\"application/xop+xml\";charset=UTF-8;start-info=\"application/soap+xml\";action=\"{action}\";boundary=\"uuid:00361b85-692d-43a1-9f17-57d70bbe26df+id=1\";");
request.Properties[HttpRequestMessageProperty.Name] = reqProps;
return null;
}
}
那我就用它
using (OperationContextScope scope = new OperationContextScope((Client as DocumentRepository_PortTypeClient).InnerChannel))
{
//I try to read header here but they are empty
var obj = OperationContext.Current.OutgoingMessageProperties;
response = Client.call(request);
}