![](/img/trans.png)
[英]Can ServiceStack.Text deserialize JSON to a custom generic type?
[英]ServiceStack return custom response when can't deserialize request
我正在使用servicestack來處理來自客戶端的xml請求,我的客戶端要求始終發送如下響應:
<?xml version="1.0" encoding="utf-8"?>
<Response>
<actionCode>01</actionCode>
<errorCode>20450</errorCode>
</Response>
無法反序列化請求時如何使用這種格式響應。 謝謝。
默認情況下,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();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.