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

标签 c# rest wcf error-handling

我正在尝试在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/

相关文章:

c# - 如何覆盖从构造函数调用的基类方法

c# - WP7 - 衡量性能改进

c# - 从 Main() 调用函数

json - 我的 API 是否应该将 JSON 数据嵌套在父对象中?

c# - C# 多线程应用程序可以为每个线程使用单独的 WorkingDirectories 吗?

ios - 如何使用 AFNetworking-2.0 执行 JSON 编码的 GET 请求?

javascript - 来自雅虎财经 API 的 400 错误请求

c# - ASP.net 中的隐藏字段长度是否有任何限制

WCF 命名管道和 Azure Web 角色

wcf - Azure 上的 WCF 使用了哪种类型的安全性且与 Silverlight 兼容?