Средство форматирования сообщений WCF не форматирует сообщение об ошибке - PullRequest
0 голосов
/ 19 июня 2020

У меня есть служба WCF, где я меняю префикс положительного ответа, однако при ответе на ошибку изменяется только часть сообщения.

<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAP-ENV:Body>
    <s:Fault
        xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
        <faultcode>s:Client</faultcode>
        <faultstring xml:lang="en-GB">Unable to satisfy web service request at this time.This may relate to the format or sequence of the requests, the status of the requested information or reflect a service issue.</faultstring>
    </s:Fault>
</SOAP-ENV:Body>

SOAP -ENV - правильный синтаксис, однако, как вы можете видеть при регистрации ошибки, префикс - s:.

Класс, который выполняет эту работу, находится здесь

public class ProposalMessage : Message
{
    private readonly Message message;

    public ProposalMessage(Message message)
    {
        this.message = message;
    }
    public override MessageHeaders Headers
    {
        get { return this.message.Headers; }
    }
    public override MessageProperties Properties
    {
        get { return this.message.Properties; }
    }
    public override MessageVersion Version
    {
        get { return this.message.Version; }
    }

    protected override void OnWriteStartBody(XmlDictionaryWriter writer)
    {
        writer.WriteStartElement("Body", "http://schemas.xmlsoap.org/soap/envelope/");
    }
    protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
    {
        this.message.WriteBodyContents(writer);
    }
    protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer)
    {
        writer.WriteStartElement("SOAP-ENV", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
        writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
        writer.WriteAttributeString("xmlns", "xsd", null, "http://www.w3.org/2001/XMLSchema");
    }
}

, и мне также нужно вырезать пространство имен этого тоже.

Я пробовал множество вещей, но ни один из них не работал.

ниже - это пример одного из методов \ вещей, которые я пробовал

protected override void OnWriteDetail(XmlDictionaryWriter writer)
{
    writer.WriteStartElement("Fault", "http://schemas.xmlsoap.org/soap/envelope/");
}

Однако это не подходит для переопределения

Посмотрев на некоторую документацию вот https://docs.microsoft.com/en-us/dotnet/api/system.servicemodel.channels.messagefault.onwritedetail?view=netframework-4.7.2 Я не могу заставить что-либо работать.

Любая помощь по форматированию сообщения об ошибке будет большой

1 Ответ

1 голос
/ 22 июня 2020

Вы можете попробовать следующее решение:

  public class CustomMessage : Message
    {
        private readonly Message message;

        public CustomMessage(Message message)
        {
            this.message = message;
        }
        public override MessageHeaders Headers
        {
            get { return this.message.Headers; }
        }
        public override MessageProperties Properties
        {
            get { return this.message.Properties; }
        }
        public override MessageVersion Version
        {
            get { return this.message.Version; }
        }
        protected override void OnWriteStartBody(XmlDictionaryWriter writer)
        {
            writer.WriteStartElement("Body", "http://schemas.xmlsoap.org/soap/envelope/");
        }
        protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
        {
            this.message.WriteBodyContents(writer);
        }
        protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer)
        {
            writer.WriteStartElement("SOAP-ENV", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
            writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
            writer.WriteAttributeString("xmlns", "xsd", null, "http://www.w3.org/2001/XMLSchema");
        }
    }

Это CustomMessage.

public class MyCustomMessageFormatter : IDispatchMessageFormatter
    {
        private readonly IDispatchMessageFormatter formatter;

        public MyCustomMessageFormatter(IDispatchMessageFormatter formatter)
        {
            this.formatter = formatter;
        }

        public void DeserializeRequest(Message message, object[] parameters)
        {
            this.formatter.DeserializeRequest(message, parameters);
        }

        public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
        {
            var message = this.formatter.SerializeReply(messageVersion, parameters, result);
            return new CustomMessage(message);
        }
    }

Это MyCustomMessageFormatter.

 [AttributeUsage(AttributeTargets.Method)]
    public class MyMessageAttribute : Attribute, IOperationBehavior
    {
        public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) { }

        public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) { }

        public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
        {
            var serializerBehavior = operationDescription.Behaviors.Find<DataContractSerializerOperationBehavior>();

            if (dispatchOperation.Formatter == null)
            {
                ((IOperationBehavior)serializerBehavior).ApplyDispatchBehavior(operationDescription, dispatchOperation);
            }

            IDispatchMessageFormatter innerDispatchFormatter = dispatchOperation.Formatter;

            dispatchOperation.Formatter = new MyCustomMessageFormatter(innerDispatchFormatter);
        }

        public void Validate(OperationDescription operationDescription) { }
    }

Это MyMessageAttribute.We добавляем MyCustomMessageFormatter к поведению.

        [MyMessage]
        public Result GetUserData(string name)
        {....

Мы добавляем поведение, которое мы только что определили, в метод.

...