简体   繁体   中英

WCF Add Namespace Attributes

I have a simple WCF that fetches two values. This is my code:

[ServiceContract]
public interface IService
{

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

And this one:

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;

  }

}

In SoapUi I have this result

<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>

But I need to be like this:

       <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>

The reason why it needs to be this specific, it's because this message is going through a middleware before it is sent to the destination. But I can't seem to find a way to insert those namespaces on my message. If I can't do it, this won't be sent. Could you please help me?

According to your description, I think you could use WCF Message Inspector. Before the client send the message. We could customize the message body.
https://docs.microsoft.com/en-us/dotnet/framework/wcf/samples/message-inspectors
based on your code, I have made a demo to add the namespace attribute. This is the client-side code. I have added service reference to the current project, so the service contract has generated in the project.

Client.

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;
    }
}

Add the attribute to the service contract.

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

Result.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM