如何在 servicestack 中逐个类型地覆盖 XML 序列化格式

chr*_*man 2 servicestack

我有一个需要自定义 XML 序列化和反序列化的类型,我想将其用作 requestDto 的属性

对于 JSON,我可以使用 JsConfig.SerializeFn,XML 是否有类似的钩子?

myt*_*thz 5

ServiceStack 在底层使用 .NET 的 XML DataContract 序列化程序。除了底层 .NET 框架实现所提供的功能外,它不可自定义。

为了支持自定义请求,您可以覆盖默认请求处理。ServiceStack 的序列化和反序列化 wiki 页面显示了自定义请求处理的不同方法:

注册自定义请求 DTO 绑定器

base.RequestBinders.Add(typeof(MyRequest), httpReq => ... requestDto);
Run Code Online (Sandbox Code Playgroud)

跳过自动反序列化并直接从请求输入流读取

告诉 ServiceStack 跳过反序列化并通过让 DTO 自己(在您的服务中)实现IRequiresRequestStream和反序列化请求来自行处理:

//Request DTO
public class Hello : IRequiresRequestStream
{
    /// <summary>
    /// The raw Http Request Input Stream
    /// </summary>
    Stream RequestStream { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

覆盖默认的 XML Content-Type 格式

如果您希望使用不同的 XML Serializer,您可以通过注册您自己的 Custom Media Type来覆盖 ServiceStack 中的默认内容类型,例如:

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);    
Run Code Online (Sandbox Code Playgroud)