【发布时间】:2015-08-31 15:21:55
【问题描述】:
我正在尝试让 SignalR 使用自定义 JsonSerializerSettings 为其有效负载,特别是我正在尝试设置 TypeNameHandling = TypeNameHandling.Auto。
问题似乎是,SignalR 将hubConnection.JsonSerializer 和GlobalHost.DependencyResolver.Resolve<JsonSerializer>() 中的设置也用于其内部数据结构,然后导致各种破坏(当我将TypeNameHandling.All 设置为最粗鲁时,内部服务器崩溃例如,但是使用TypeNameHandling.Auto 我也会遇到问题,尤其是在涉及IProgress<> 回调时)。
有什么解决方法还是我做错了?
演示示例代码:
服务器:
class Program
{
static void Main(string[] args)
{
using (WebApp.Start("http://localhost:8080"))
{
Console.ReadLine();
}
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
var hubConfig = new HubConfiguration()
{
EnableDetailedErrors = true
};
GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), ConverterSettings.GetSerializer);
app.MapSignalR(hubConfig);
}
}
public interface IFoo
{
string Val { get; set; }
}
public class Foo : IFoo
{
public string Val { get; set; }
}
public class MyHub : Hub
{
public IFoo Send()
{
return new Foo { Val = "Hello World" };
}
}
客户:
class Program
{
static void Main(string[] args)
{
Task.Run(async () => await Start()).Wait();
}
public static async Task Start()
{
var hubConnection = new HubConnection("http://localhost:8080");
hubConnection.JsonSerializer = ConverterSettings.GetSerializer();
var proxy = hubConnection.CreateHubProxy("MyHub");
await hubConnection.Start();
var result = await proxy.Invoke<IFoo>("Send");
Console.WriteLine(result.GetType());
}
共享:
public static class ConverterSettings
{
public static JsonSerializer GetSerializer()
{
return JsonSerializer.Create(new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All
});
}
}
【问题讨论】:
-
有什么特别的原因你不想使用 SignalR 的默认 Json 序列化器吗?
-
@Matei_Radu 因为它使用
TypenameHandling.None,我需要Auto。 -
我没有 SignalR 来测试;问题是您需要 root json 对象或某些嵌套对象上的
$type属性吗?如果是前者,有什么办法可以放宽这个要求,也许通过返回一个包装对象作为根? -
@dbc 一旦我开始将每个参数和返回值打包到它自己的处理(反)序列化的小包装器中,我不妨将 SignalR 完全扔出窗外……或者更多只要没有任何自动化的方法可以做到这一点。要求是我可以将接口反序列化为其确切类型。
-
您只需要一个通用包装器:
public class Data<T> { public T data { get; set; } }。这里的困难在于,即使你设置了TypenameHandling.Auto(我知道如何为你做),它也不适用于根对象,除非 SignalR 在内部调用specific overload ofSerialize。
标签: c# json json.net signalr .net-4.5