gpt4 book ai didi

c# - IErrorHandler WCF配置为返回文本/纯文本

转载 作者:行者123 更新时间:2023-12-03 07:52:59 25 4
gpt4 key购买 nike

我正在尝试在wcf服务中强加自定义错误处理程序fo rest endpoin以在错误时返回未包装的字符串

        public void ProvideFault(Exception error,
MessageVersion version,
ref Message fault)
{
fault = CreateError(error.Message);
SetContentType();
}

private static void SetContentType()
{
if (WebOperationContext.Current != null)
{
var response = WebOperationContext.Current.OutgoingResponse;
response.ContentType = "text/plain";
}
}

private static Message CreateError(string message)
{
var fault = Message.CreateMessage(MessageVersion.None, "", message);
return fault;
}

此代码导致响应头为“文本/纯文本”,但错误消息仍被序列化为xml
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Bad Request</string>

当我将原始格式添加到创建的消息时
private static Message CreateError(string message)
{
var fault = Message.CreateMessage(MessageVersion.None, "", message);
fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw));
return fault;
}

服务停止返回。从WCF返回未包装的字符串错误的方法是什么?从ystem.ServiceModel.Channels,m.b派生有一个内部StringMessage类。我可以以某种方式实例化它?

最佳答案

尝试使用本文介绍的方法:

https://www.codeproject.com/Articles/34632/How-to-Pass-Arbitrary-Data-in-a-Message-Object-usi

private static Message CreateError(string message)
{
var fault = Message.CreateMessage(MessageVersion.None, "", new TextBodyWriter(message));
fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw));
return fault;
}

// source: https://www.codeproject.com/Articles/34632/How-to-Pass-Arbitrary-Data-in-a-Message-Object-usi
public class TextBodyWriter : BodyWriter
{
byte[] messageBytes;

public TextBodyWriter(string message)
: base(true)
{
this.messageBytes = Encoding.UTF8.GetBytes(message);
}

protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
writer.WriteStartElement("Binary");
writer.WriteBase64(this.messageBytes, 0, this.messageBytes.Length);
writer.WriteEndElement();
}
}

关于c# - IErrorHandler WCF配置为返回文本/纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52968569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com