我有一个使用SignalR 2.x的非常基本的自托管 Web服务,配置如下:
服务器:
internal class WebService
{
public void Configuration( IAppBuilder app )
{
var config = new HttpConfiguration { DependencyResolver = new ControllerResolver() };
config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Objects;
config.Routes.MapHttpRoute( "Default", "{controller}/{id}", new { id = RouteParameter.Optional } );
app.UseWebApi( config );
app.MapConnection<EventDispatcher>( "", new ConnectionConfiguration { EnableCrossDomain = true } );
GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => JsonSerializer.Create(new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
}));
app.MapHubs();
}
}
发送消息的服务器代码:
public class Notifier
{
static readonly IPersistentConnectionContext Context = GlobalHost.ConnectionManager.GetConnectionContext<EventDispatcher>();
public static void NotifyAll( NotificationType type, object obj )
{
Context.Connection.Broadcast( ConstructEvent( type, obj ) );
}
public static object ConstructEvent( NotificationType type, object obj )
{
var notevent = new { Event = type.ToString(), Data = obj };
return notevent;
}
}
客户:
void connect()
{
var _eventHandler = new Connection(Address);
_eventHandler.JsonSerializer.TypeNameHandling = TypeNameHandling.Objects;
_eventHandler.Received += eventHandler_Received;
_eventHandler.Start().Wait();
}
Web 服务很好地返回了类型化的 JSON,但 SignalR 发送的更新是纯 JSON。我在这里错过了什么吗?