WCF Добавить атрибуты пространства имен - PullRequest
0 голосов
/ 17 октября 2018

У меня есть простой WCF, который выбирает два значения.Это мой код:

[ServiceContract]
public interface IService
{

  [OperationContract]    
  List<string> comunicarAreaContencaoResponse(string Result, string Obs);   
}

А вот этот:

public class Service : IService
{

  public List<string> comunicarAreaContencaoResponse(string Result, string 
  Obs)
  {
    List<string> ListResultados = new List<string>();

    if (Result != null)
    {
        ListResultados.Add(Result);
    }

    if (Obs != null)
    {
        ListResultados.Add(Obs);
    }

    return ListResultados;

  }

}

В SoapUi у меня есть такой результат

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
 xmlns:tem="http://tempuri.org/">
   <soapenv:Header/>
     <soapenv:Body>
        <tem:comunicarAreaContencaoResponse>
          <!--Optional:-->
           <tem:Result>?</tem:Result>
          <!--Optional:-->
           <tem:Obs>?</tem:Obs>
        </tem:comunicarAreaContencaoResponse>
    </soapenv:Body>
 </soapenv:Envelope>

Но мне нужно быть таким:

       <soapenv:Envelope 
         xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
          xmlns:tem="http://tempuri.org/">
           <soapenv:Header/>
            <soapenv:Body>
              <tem:comunicarAreaContencaoResponse
               xmlns="http://www.outsystems.com"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema">
                 <tem:Result>false</tem:Result>
                 <tem:Obs />
        </tem:comunicarAreaContencaoResponse>
       </soapenv:Body>
     </soapenv:Envelope>

Причина, по которой он должен быть таким конкретным, заключается в том, что это сообщение проходит через промежуточное ПО, прежде чем оно будет отправлено в пункт назначения.Но я не могу найти способ вставить эти пространства имен в мое сообщение.Если я не могу сделать это, это не будет отправлено.Не могли бы вы помочь мне?

1 Ответ

0 голосов
/ 19 октября 2018

Согласно вашему описанию, я думаю, вы могли бы использовать инспектор сообщений WCF.Перед тем как клиент отправит сообщение.Мы могли бы настроить тело сообщения.
https://docs.microsoft.com/en-us/dotnet/framework/wcf/samples/message-inspectors
на основе вашего кода, я сделал демо для добавления атрибута пространства имен.Это код на стороне клиента.Я добавил сервисную ссылку в текущий проект, поэтому в проекте создан контракт на обслуживание.

Клиент.

static void Main(string[] args)
    {
        ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();

        try
        {
            var result = client.comunicarAreaContencaoResponse("Hello","World");
            foreach (var item in result)
            {
                Console.WriteLine(item);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }



public class ClientMessageLogger : IClientMessageInspector
    {
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            string result = $"server reply message:\n{reply}\n";
            Console.WriteLine(result);
        }

    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {

        // Read reply payload 
        XmlDocument doc = new XmlDocument();
        MemoryStream ms = new MemoryStream();
        XmlWriter writer = XmlWriter.Create(ms);
        request.WriteMessage(writer);
        writer.Flush();
        ms.Position = 0;
        doc.Load(ms);

        // Change Body logic 
        ChangeMessage(doc);

        // Write the reply payload 
        ms.SetLength(0);
        writer = XmlWriter.Create(ms);

        doc.WriteTo(writer);
        writer.Flush();
        ms.Position = 0;
        XmlReader reader = XmlReader.Create(ms);
        request = System.ServiceModel.Channels.Message.CreateMessage(reader, int.MaxValue, request.Version);
        string result = $"client ready to send message:\n{request}\n";
        Console.WriteLine(result);
        return null;
    }
    void ChangeMessage(XmlDocument doc)
    {
        XmlElement element = (XmlElement)doc.GetElementsByTagName("comunicarAreaContencaoResponse").Item(0);
        if (element!=null)
        {
            element.SetAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
            element.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            element.Attributes.RemoveNamedItem("xmlns:i");
        }
    }
}
public class CustContractBehaviorAttribute : Attribute, IContractBehavior, IContractBehaviorAttribute
{
    public Type TargetContract => typeof(IService);

    public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {
        return;
    }

    public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.ClientMessageInspectors.Add(new ClientMessageLogger());
    }

    public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
    {
        return;
    }

    public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
    {
        return;
    }
}

Добавьте атрибут в контракт на обслуживание.

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="ServiceReference1.IService")]
[CustContractBehavior]
public interface IService {
    }

Результат.

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...