当无法反序列化请求时,ServiceStack返回自定义响应

时间:2017-06-22 08:00:29

标签: c# serialization servicestack servicestack-text

我正在使用servicestack处理来自客户端的xml请求,我的客户端总是需要发送响应:

<?xml version="1.0" encoding="utf-8"?>
<Response>
<actionCode>01</actionCode>
<errorCode>20450</errorCode>
</Response>

当无法反序列化请求时,如何使用此格式进行响应。 谢谢。

1 个答案:

答案 0 :(得分:0)

默认情况下,ServiceStack返回Response DTO的DataContract序列化版本,因此如果您没有通过返回所需XML格式的DTO来获得所需的XML输出,例如:

public class Response 
{
    public string actionCode { get; set; }
    public string errorCode { get; set; }
}

如果您需要控制确切的XML响应,您的服务可以返回您想要的XML字符串文字,例如:

[XmlOnly]
public object Any(MyRequest request)
{
    ....
    return @$"<?xml version="1.0" encoding="utf-8"?>
    <Response>
            <actionCode>{actionCode}</actionCode>
            <errorCode>{errorCode}</errorCode>
    </Response>";
}

编写自定义错误响应是非常不推荐的,因为它会破坏ServiceStack客户端,现有端点/格式等。但您可以强制编写自定义XML错误,例如反序列化错误,例如:

UncaughtExceptionHandlers.Add((req, res, operationName, ex) =>
{
    res.ContentType = MimeTypes.Xml;
    res.Write($@"<?xml version=""1.0"" encoding=""utf-8"" ?>
        <Response>
            <actionCode>{ex.Message}</actionCode>
            <errorCode>{ex.GetType().Name}</errorCode>
        </Response>");
    res.EndRequest();
});
相关问题