2
我使用SignalR 2.x具有以下配置一個非常基本的自託管的Web服務:SignalR和類型的對象
服務器:
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();
}
}
Server代碼來發送消息:
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。我在這裏錯過了什麼嗎?
我想你的樣本客戶機,並將其發送的Json類型化 數據=%7B%22%24type% 22%3A%22%3C%3Ef__AnonymousType0%602%5B%5BSystem.Int32%2C + mscorlib程序%5D%2C%5BSystem.String%2C + mscorlib程序%5D%5D%2C + Microsoft.AspNet.SignalR.Client.Samples% 22%2C 22%22%3A1%2C 22%22%3A%22首先+消息%22%7D –
事實證明,問題是我通過'Notifier.NotifyAll()'調用'PersistentConnection'控制器。出於某種原因,它然後使用默認的JSonParser。我嘗試在'PersistentConnection'的'overrid Initialize'內設置'TypeNameHandling',但這沒有任何作用。 – dsfgsho