2

I'm using servicestack to handle xml request from client, my client require always send response like that:

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

How can I response with this format when can't deserialize request. Thank you.

1 Answers1

0

By default ServiceStack returns a DataContract serialized version of the Response DTO, so if you don't get the desired XML output by returning a DTO in the shape of XML you want, e.g:

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

If you need to control the exact XML response your Services can just return the XML string literal you want, e.g:

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

Writing a Custom Error Response is highly unrecommended as it will break ServiceStack clients, existing endpoints / formats, etc. But you can force writing a Custom XML Error for Uncaught Exceptions like deserialization errors with something like:

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();
});
mythz
  • 141,670
  • 29
  • 246
  • 390
  • But when can''t deserialize request to MyRequest, ServiceStack will return a exception response. – Thang Trinh Xuan Jun 22 '17 at 15:10
  • Yeah ServiceStack needs to be able to deserialize the request, if you want to deserialize the request yourself you can [implement IRequiresRequestStream](http://docs.servicestack.net/serialization-deserialization#reading-directly-from-the-request-stream). – mythz Jun 22 '17 at 15:12
  • Hi, I don't need to deserialize the request myself but I want to handle exception when deserialize and send a custom response instead of build in exp exception response. – Thang Trinh Xuan Jun 22 '17 at 15:42
  • @ThangTrinhXuan that's not supported but you can look at adding a `AppHost.UncaughtExceptionHandlers` handler and write the XML directly to the response as shown in the updated answer, but this is highly unrecommended and not something we support. – mythz Jun 22 '17 at 16:01