How can I override the XML serialization format on a type by type basis in servicestack

a 夏天 提交于 2019-12-18 09:24:34

问题


I have a type that requires custom XML serialization & deserialization that I want to use as a property on my requestDto

For JSON i can use JsConfig.SerializeFn, is there a similar hook for XML?


回答1:


ServiceStack uses .NET's XML DataContract serializer under the hood. It is not customizable beyond what is offered by the underlying .NET's Framework implementation.

In order to support custom requests you can override the default request handling. ServiceStack's Serialization and Deserialization wiki page shows different ways to customize the request handling:

Register a Custom Request DTO binder

base.RequestBinders.Add(typeof(MyRequest), httpReq => ... requestDto);

Skip auto deserialization and read directly from the Request InputStream

Tell ServiceStack to skip deserialization and handle it yourself by getting your DTO to implement IRequiresRequestStream and deserialize the request yourself (in your service):

//Request DTO
public class Hello : IRequiresRequestStream
{
    /// <summary>
    /// The raw Http Request Input Stream
    /// </summary>
    Stream RequestStream { get; set; }
}

Override the default XML Content-Type format

If you would prefer to use a different XML Serializer, you can override the default content-types in ServiceStack by registering your own Custom Media Type, e.g:

string contentType = "application/xml";
var serialize = (IRequest request, object response, Stream stream) => ...;
var deserialize = (Type type, Stream stream) => ...;

//In AppHost.Configure method pass two delegates for serialization and deserialization
this.ContentTypes.Register(contentType, serialize, deserialize);    


来源:https://stackoverflow.com/questions/13493594/how-can-i-override-the-xml-serialization-format-on-a-type-by-type-basis-in-servi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!