ASP.NET Web API:使用默认的序列化程序

时间:2013-03-28 15:05:36

标签: json serialization asp.net-web-api signalr

是否有一种使用ASP.NET Web API默认序列化程序的简单方法?

在WebApiConfig.cs中以这种方式配置我的

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

完美无缺。我想要做的是在特定情况下手动使用完全相同的序列化程序。如果由于某种原因配置发生变化,手动序列化必须反映这些变化而不必关心它。

为了更准确地说明我的意图,我想在将新资源保​​存到数据库之后将其发送到SignalR Hub。它们需要以与使用GET请求时ASP.NET Web API相同的方式进行序列化。

3 个答案:

答案 0 :(得分:0)

您可以在应用程序启动时使用自定义JSON.NET序列化程序设置在SignalR的依赖项解析程序中注册您自己的IJsonSerializer

//...
using Microsoft.AspNet.SignalR.Json;
using Newtonsoft.Json;

//...

    protected void Application_Start(object sender, EventArgs e)
    {

        var settings = new JsonSerializerSettings();
        settings.Converters.Add(new StringEnumConverter());
        settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        var serializer = new JsonNetSerializer(settings);

        GlobalHost.DependencyResolver.Register(typeof(IJsonSerializer), () => serializer);

        RouteTable.Routes.MapHubs();

        //...

答案 1 :(得分:0)

我找到了一个基于此错误报告的解决方案:https://github.com/SignalR/SignalR/issues/500

首先,创建一个自定义IContractResolver

public class SignalRContractResolver : IContractResolver
{
    private readonly Assembly _assembly;
    private readonly IContractResolver _camelCaseContractResolver;
    private readonly IContractResolver _defaultContractSerializer;

    public SignalRContractResolver()
    {
        _defaultContractSerializer = new DefaultContractResolver();
        _camelCaseContractResolver = new CamelCasePropertyNamesContractResolver();
        _assembly = typeof(Connection).Assembly;
    }

    public JsonContract ResolveContract(Type type)
    {
        if (type.Assembly.Equals(_assembly))
            return _defaultContractSerializer.ResolveContract(type);

        return _camelCaseContractResolver.ResolveContract(type);
    }
}

接下来,在ApplicationStart中注册它

    var settings = new JsonSerializerSettings();
    settings.Converters.Add(new StringEnumConverter());
    settings.ContractResolver = new SignalRContractResolver();

    var serializer = new JsonNetSerializer(settings);

    GlobalHost.DependencyResolver.Register(typeof(IJsonSerializer), () => serializer);

感谢halter73让我指向正确的方向!

答案 2 :(得分:0)

我发现了这个并且它运行良好

var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
formatter.SerializerSettings = new JsonSerializerSettings
{
    Formatting = Formatting.Indented,
    TypeNameHandling = TypeNameHandling.Objects,
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

这必须放在" Global.asax.cs"文件" Application_Start"功能