Soapheader не может быть сериализован - PullRequest
0 голосов
/ 27 июня 2019

я пытаюсь разработать SOAP-клиент, он хотел, чтобы его собственный soapheader (i.e.usercred) был сериализован, но после этого я получаю это как ошибку System.Runtime.Serialization.InvalidDataContractException: 'Type' ConsoleApp1.Program + usercred 'не может наследоваться от типа, который не помечен как DataContractAttribute или SerializableAttribute. Попробуйте пометить базовый тип System.Web.Services.Protocols.SoapHeader с помощью DataContractAttribute или SerializableAttribute или удалить их из производного типа. '

он хочет, чтобы мыльница также была сериализована, пожалуйста, помогите

1 Ответ

0 голосов
/ 27 июня 2019

Есть несколько способов добавить пользовательский заголовок супа в ваш запрос супа.

Например, вы можете создать запрос супа, используя HTTPRequest, где вы можете создать конверт супа, как вы хотите. Клиент для отправки SOAP-запроса и получения ответа

        public override string Process(string UserName,string Password)
    {
        string uri = "https://serviceURL";

        HttpWebRequest req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(uri));
        req.ContentType = "application/soap+xml; charset=utf-8";            
        req.Method = "POST";
        string soapRequest = BuildSoapRequest(UserName,Password);
        StreamWriter stm = new StreamWriter(req.GetRequestStream(), Encoding.UTF8);
        stm.Write(soapRequest);
        stm.Close();

        try
        {
            HttpWebResponse wr = (HttpWebResponse)req.GetResponse();
            StreamReader srd = new StreamReader(wr.GetResponseStream());

            string response = srd.ReadToEnd();
            return ExtractResponse(response);
        }
        catch (WebException e)
        {
            string error = "";
            HttpWebResponse errRsp = (HttpWebResponse)e.Response;
            if (errRsp != null)
            {
                using (StreamReader rdr = new StreamReader(errRsp.GetResponseStream()))
                {
                    string line;
                    while ((line = rdr.ReadLine()) != null)
                    {
                        error += line;
                    }
                }
            }
            throw new Exception(e.Message + "<br/> " + error);
        }
        catch (Exception e)
        {
            throw e;
        }
    }
    private string BuildSoapRequest(string UserName,string Password)
    {
        StringBuilder soapRequest = new StringBuilder();

        soapRequest.Append("<soap:Envelope xmlns:cor=\"http://www.caqh.org/SOAP/WSDL/CORERule2.2.0.xsd\" xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:tem=\"http://tempuri.org/\">");
        soapRequest.Append("<soap:Header>");
        soapRequest.Append("<wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">");
        soapRequest.Append("<wsse:UsernameToken>");
        soapRequest.Append("<wsse:Username>" + UserName + "</wsse:Username>");
        soapRequest.Append("<wsse:Password>" + Password + "</wsse:Password>");
        soapRequest.Append("</wsse:UsernameToken>");
        soapRequest.Append("</wsse:Security>");
        soapRequest.Append("</soap:Header>");
        soapRequest.Append("<soap:Body>");
        soapRequest.Append("</soap:Body>");
        soapRequest.Append("</soap:Envelope>");

        return soapRequest.ToString();
    }

     private static string ExtractResponse(string soap)
    {

    }

Если вы используете службу WCF, вы можете добавить свое поведение в свой запрос. Пользовательское поведение конечной точки не используется в клиенте WCF со ссылкой на службу

public class CustomClientBehavior : IEndpointBehavior
{
    string _username;
    string _password;
    public CustomClientBehavior(string username, string password)
    {
        _username = username;
        _password = password;
    }
    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {

    }
    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        CustomInspector inspector = new CustomInspector(_username, _password);
        clientRuntime.MessageInspectors.Add(inspector);
    }
    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {

    }
    public void Validate(ServiceEndpoint endpoint)
    {

    }
}

public class CustomClientBehaviorExtensionElement : BehaviorExtensionElement
{
    string _username;
    string _password;

    public CustomClientBehaviorExtensionElement(string username, string password)
    {
        _username = username;
        _password = password;
    }

    public override Type BehaviorType
    {
        get { return typeof(CustomClientBehavior); }
    }

    protected override object CreateBehavior()
    {
        return new CustomClientBehavior(_username, _password);
    }
}

public class CustomInspector : IClientMessageInspector
{
    string _username;
    string _password;

    public CustomInspector(string username, string password)
    {
        _username = username;
        _password = password;
    }

    public void AfterReceiveReply(ref Message reply, object correlationState)
    {
        return;
    }

    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        request.Headers.Clear();
        string headerText = "<wsse:UsernameToken xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">" +
                                "<wsse:Username>{0}</wsse:Username>" +
                                "<wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">" +
                                "{1}</wsse:Password>" +
                            "</wsse:UsernameToken>";
        headerText = string.Format(headerText, _username, _password);
        XmlDocument MyDoc = new XmlDocument();
        MyDoc.LoadXml(headerText);
        XmlElement myElement = MyDoc.DocumentElement;
        System.ServiceModel.Channels.MessageHeader myHeader = MessageHeader.CreateHeader("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", myElement, false);
        request.Headers.Add(myHeader);
        return Convert.DBNull;
    }
}

Тестовый клиент должен быть похож на

TestService.Client objClient = new TestService.Client();
objClient.Endpoint.Behaviors.Add(new CustomClientBehavior(UserName, Password));

Вы также можете попробовать Аутентификация заголовков WebService

...