[英]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.