[英]ServiceStack: Property in request DTO becomes null if type is abstract
我有一个基于ServiceStack 3的客户端-服务器体系结构。 我正在尝试创建一个服务,该服务的请求DTO包含具有抽象类型的属性,并通过两个不同的具体类来实现它。 抽象类型可以是抽象类或接口。 但是,无论哪种情况,服务器都会在属性中收到一个空对象。
客户机和服务器都引用了三个程序集和相应的名称空间: TestClient
, Server
和CommonLib
。
也就是说,分布在三个程序集中:
namespace CommonLib.Services
{
public class GetThing : IReturn<GetThingResponse> // request DTO
{
public IThisOrThat Context { get; set; }
}
public class GetThingResponse
{
public Dictionary<int, string> Result { get; private set; }
public GetThingResponse(Dictionary<int, string> result) // response DTO
{
Result = result;
}
}
}
namespace CommonLib
{
public interface IThisOrThat { }
public class This : IThisOrThat { } // and so forth
}
namespace Server.Services
{
public class GetThing Service : IService
{
public object Get(GetThing request)
{
var foo = request.Context; // this is null
}
}
}
namespace TestClient
{
class Program
{
public const string WSURL = "http://localhost:61435/";
static void Main(string[] args)
{
using (var client = new JsonServiceClient(WSURL))
{
var result = client.Get(new GetThing
{
Context = new CommonLib.This("context info")
});
}
}
如果我将GetThing
的Context
属性更改为This
而不是IThisOrThat
类型,则可以使用。 将其保留为接口,或者将IThisOrThat
更改为抽象类,将导致数据以null
形式传输。
我假设这是一个序列化问题。 我尝试将接口更改为抽象类,并使用适当的KnownType
属性对其进行装饰,但是ServiceStack的序列化程序似乎并未从中受益。 有什么技巧可以做到这一点吗?
您需要启用JsConfig.IncludeTypeInfo = true;
在客户端,因此序列化程序将类型信息包含在请求中。 这将在类型定义中添加一个额外的属性( __type
),以便服务知道将其键入为什么。
当前失败,因为默认情况下请求不提供类型信息以将对象反序列化为实现接口的类。 这是先前提出的问题。
问题是当JSON客户端发出请求时,它将序列化实现IThisOrThat
的类,例如您的This
类。 但是当到达另一端时,ServiceStack.Text不知道将对象反序列化成什么。 类型信息丢失,因此它不知道它是哪种IThisOrThat
。 因此,在请求中没有其他__type
information属性的情况发生了:
场景:
interface ISomething
{
string Name;
}
class MySomething : ISomething
{
public string Name { get; set; }
public int Age { get; set; }
}
class MySomethingElse : ISomething
{
public string Name { get; set; }
public int Size { get; set; }
}
然后,使用类型对象从JsonServiceClient进行调用
client.Get(new MySomething { Name: "Duck", Age: 20 });
发送的JSON将是{ "Name":"Duck", "Age":20 }
解串器现在选择哪种类型? 可能是MySomething
或MySomethingElse
,甚至可能是尚不知道的另一个ISomething
。 因此,因为无法确定结果只是null
。
通常,接口和DTO不会混合使用, 请参见此处 。
我遇到了类似的问题,并且意识到我没有{ 组; }应用于响应DTO,所以我对象的结果始终为null ...
认为此信息也可以帮助任何人搜索此信息...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.