从客户端消息检查器访问 ClientCredential 属性

rau*_*and 2 c# wcf

我可以从客户端消息检查器引用代理客户端实例吗?

原因是,我想访问以下属性的值:

ClientCredentials.UserName.UserName  
ClientCredentials.UserName.Password 
Run Code Online (Sandbox Code Playgroud)

谢谢

rau*_*and 5

我通过从自定义 EndpointBehavior 传递对“ClientCredentials”的引用,设法从检查器中检索凭据:

自定义行为:

public class CustomEndpointBehaviour:IEndpointBehavior
{
    public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
    {
        ClientCredentials credentials = endpoint.Behaviors.Find<ClientCredentials>();
        clientRuntime.MessageInspectors.Add(new CustomMessageInspector(credentials));
    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
    {
    }

    public void Validate(ServiceEndpoint endpoint)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

和检查员:

public class CustomMessageInspector : IClientMessageInspector
{
    ClientCredentials crendentials = null;

    public CustomMessageInspector(ClientCredentials credentials)
    {
        this.crendentials = credentials;
    }

    public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
    {
    }

    public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
    {
        string userName = "";
        string passWord = "";

        if (!(crendentials == null))
        {
            userName = crendentials.UserName.UserName;
            passWord = crendentials.UserName.Password;
        }
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)