C#WCF服务引用-无法创建UserNameToken

C#WCF服务引用-无法创建UserNameToken,c#,web-services,wcf,soap,usernametoken,C#,Web Services,Wcf,Soap,Usernametoken,在我的桌面应用程序(C#、WPF、WCF、.NET4.0)中,我添加了一个服务引用 这是在SOAP信封头中使用证书和UserNameToken的Web服务(SOAP) 我使用此web服务的WSDL添加服务引用(解决方案->服务引用->添加服务引用)。 在我的app.config中,我得到: <customBinding> <binding name="tmsIntegrationServiceSOAP"> <!-- WsdlImpo

在我的桌面应用程序(C#、WPF、WCF、.NET4.0)中,我添加了一个服务引用

这是在SOAP信封头中使用证书和UserNameToken的Web服务(SOAP)

我使用此web服务的WSDL添加服务引用(解决方案->服务引用->添加服务引用)。 在我的app.config中,我得到:

    <customBinding>
<binding name="tmsIntegrationServiceSOAP">
          <!--    WsdlImporter encountered unrecognized policy assertions in ServiceDescription 'urn:CDM/tmsIntegrationService/':    -->
          <!--    <wsdl:binding name='tmsIntegrationServiceSOAP'>    -->
          <!--        <sp:SupportingTokens xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">..</sp:SupportingTokens>    -->
          <mtomMessageEncoding messageVersion="Soap11" />
          <httpsTransport />
        </binding>
      </customBinding>

<endpoint address="https://XXX/CDM/tmsIntegrationService"
        binding="customBinding" bindingConfiguration="tmsIntegrationServiceSOAP"
        contract="RABEN.GS1.tmsIntegrationService" name="tmsIntegrationServiceSOAP" />
当我获得请求XML(带有消息检查器)时,我看到soap头中没有UserNameToken

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">urn:CDM/tmsIntegrationService/importTransportInstruction</Action>
    <VsDebuggerCausalityData xmlns="http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink">uIDPoy3hcoBMqQ5Kme7yqEiHKs0AAAAAyxy+QnWD8U60kqJZWaGfvYD8RN14nUVIjC0RuEyVBa8ACQAA</VsDebuggerCausalityData>
  </s:Header>
  <s:Body ...

urn:CDM/tmsIntegrationService/importTransportInstruction
UIDPOY3HCOMQ5KME7YQEIHKS0AAAAAYXY+QNWD8U60KQJZWAGFYD8RN14NUVIJC0RUEYVBA8ACQAA
但它没有效果-请求XML中没有用户名令牌:

<s:Header>
    <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">urn:CDM/tmsIntegrationService/importTransportInstruction</Action>
    <VsDebuggerCausalityData xmlns="http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink">uIDPo0wJNixU4QRBhGEUAC3pw50AAAAA/fPJ+e50KUSGbYXwcmoGwgqymCvLXJZIhKg/nKdV97cACQAA</VsDebuggerCausalityData>
  </s:Header>

urn:CDM/tmsIntegrationService/importTransportInstruction
UIDPO0WJNIXU4QRBHGEUAC3PW50AAAA/fPJ+e50KUSGbYXwcmoGwgqymCvLXJZIhKg/nKdV97cACQAA

但是如果您通过单击“解决方案资源管理器”“添加服务”引用添加,会发生什么,它会告诉您什么?。或者您没有此选项。

要修改SOAP头,您需要实现IClientMessageInspector 为此,创建新的类MessageInspector并添加 其中嵌套了以下三个类:

public class CustomMessageHeader : MessageHeader
        {
            private const string NAMESPACE_SECURITY = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
            public CustomMessageHeader()
            {
            }
            public override string Name
            {
                get { return "wsse:Security"; }
            }
            public override string Namespace
            {
                get { return ""; }
            }
            protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
            {
                writer.WriteAttributeString("xmlns", "wsse", null, NAMESPACE_SECURITY);
                writer.WriteStartElement("wsse:UsernameToken");
                writer.WriteElementString("wsse:Username", "YOUR_USERNAME");
                writer.WriteElementString("wsse:Password", "YOUR_PASSWORD");
                writer.WriteEndElement();
            }
        }
public class ClientMessageInspector : IClientMessageInspector
        {
            public object BeforeSendRequest(ref Message request, IClientChannel channel)
            {
                CustomMessageHeader header = new CustomMessageHeader();
                request.Headers.RemoveAt(0);
                request.Headers.Add(header);
                return request;
            }
public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
            {
            }
        }
public class CustomEndpointBehavior : IEndpointBehavior
        {
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
            {
                clientRuntime.ClientMessageInspectors.Add(new ClientMessageInspector());
            }
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
            {
            }

            public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
            {
            }

            public void Validate(ServiceEndpoint endpoint)
            {
            }
}
要触发调用此类,请在主类中添加新的端点行为

serviceClient.Endpoint.EndpointBehaviors.Add(new CustomEndpointBehavior());

我将问题编辑得更清楚:我使用此web服务的WSDL添加服务引用(解决方案->服务引用->添加服务引用)。当我添加服务引用并执行此操作时,没有错误。如果答案为“是”,请请求接受您的证书并输入用户和密码。你可以在没有其他任何东西的情况下引用它。对不起,我的英语很抱歉检查一下,您是否尝试过在自定义绑定中使用
而不是
?我尝试过这个(请参见编辑2017-06-21 20:58)您的编辑仍然包含MTOMMessageEncoding对不起,我添加了带有文本消息编码的新编辑(编辑2017-06-21 21:36)-无效:(
<wsHttpBinding>
        <binding name="RabenBinding">
          <security mode="TransportWithMessageCredential">
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </wsHttpBinding>

<endpoint address="https://XXX/CDM/tmsIntegrationService"
        binding="wsHttpBinding" bindingConfiguration="RabenBinding"
        contract="RABEN.GS1.tmsIntegrationService" name="tmsIntegrationServiceSOAP" />
<s:Header>
    <a:Action s:mustUnderstand="1">urn:CDM/tmsIntegrationService/importTransportInstruction</a:Action>
    <a:MessageID>urn:uuid:701a0fff-c4aa-4f37-a299-ec6d272e51e7</a:MessageID>
    <a:ReplyTo>
      <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
    </a:ReplyTo>
  </s:Header>
<behaviors>
      <endpointBehaviors>
        <behavior name="RabenBehavior">
          <clientCredentials>
            <clientCertificate findValue="this is footprint of certificate"
              storeLocation="CurrentUser" storeName="My" x509FindType="FindByThumbprint" />
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>
<endpoint address="https://XXX/CDM/tmsIntegrationService"
        behaviorConfiguration="RabenBehavior" binding="wsHttpBinding"
        bindingConfiguration="RabenBinding" contract="RABEN.GS1.tmsIntegrationService"
        name="tmsIntegrationServiceSOAP" />
<binding name="myCustomBindingConfig">
          <security defaultAlgorithmSuite="Default"
                    authenticationMode="UserNameOverTransport"
            requireDerivedKeys="true"
          includeTimestamp="false" messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10" />
          <mtomMessageEncoding messageVersion="Soap11" />
          <httpsTransport maxReceivedMessageSize="2000000000" />
        </binding>
<s:Header>
    <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">urn:CDM/tmsIntegrationService/importTransportInstruction</Action>
    <VsDebuggerCausalityData xmlns="http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink">uIDPo0OlG2DVOLdKniJmYU2kvwUAAAAAujMM+x53aEWJYYd4GKyk+PlCKXIih9xLrE0V5TayKhQACQAA</VsDebuggerCausalityData>
  </s:Header>
<binding name="tmsIntegrationServiceSOAP">
          <!--    WsdlImporter encountered unrecognized policy assertions in ServiceDescription 'urn:CDM/tmsIntegrationService/':    -->
          <!--    <wsdl:binding name='tmsIntegrationServiceSOAP'>    -->
          <!--        <sp:SupportingTokens xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">..</sp:SupportingTokens>    -->
          <textMessageEncoding messageVersion="Soap11" />
          <httpsTransport />
        </binding>
<s:Header>
    <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">urn:CDM/tmsIntegrationService/importTransportInstruction</Action>
    <VsDebuggerCausalityData xmlns="http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink">uIDPo0wJNixU4QRBhGEUAC3pw50AAAAA/fPJ+e50KUSGbYXwcmoGwgqymCvLXJZIhKg/nKdV97cACQAA</VsDebuggerCausalityData>
  </s:Header>
public class CustomMessageHeader : MessageHeader
        {
            private const string NAMESPACE_SECURITY = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
            public CustomMessageHeader()
            {
            }
            public override string Name
            {
                get { return "wsse:Security"; }
            }
            public override string Namespace
            {
                get { return ""; }
            }
            protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
            {
                writer.WriteAttributeString("xmlns", "wsse", null, NAMESPACE_SECURITY);
                writer.WriteStartElement("wsse:UsernameToken");
                writer.WriteElementString("wsse:Username", "YOUR_USERNAME");
                writer.WriteElementString("wsse:Password", "YOUR_PASSWORD");
                writer.WriteEndElement();
            }
        }
public class ClientMessageInspector : IClientMessageInspector
        {
            public object BeforeSendRequest(ref Message request, IClientChannel channel)
            {
                CustomMessageHeader header = new CustomMessageHeader();
                request.Headers.RemoveAt(0);
                request.Headers.Add(header);
                return request;
            }
public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
            {
            }
        }
public class CustomEndpointBehavior : IEndpointBehavior
        {
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
            {
                clientRuntime.ClientMessageInspectors.Add(new ClientMessageInspector());
            }
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
            {
            }

            public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
            {
            }

            public void Validate(ServiceEndpoint endpoint)
            {
            }
}
serviceClient.Endpoint.EndpointBehaviors.Add(new CustomEndpointBehavior());