介尘部落

文学|音乐|休闲娱乐|计算机技术|地球科学|社会学——知识成就命运


Automatic camel-casing of properties with SignalR hubs

定义ContractResolver ,继承 IContractResolver

using System;
using System.Reflection;
using Newtonsoft.Json.Serialization;
using SignalR;

namespace Loveboat.Configuration
{
    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;
        }

        #region IContractResolver Members

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

            return _camelCaseContractResolver.ResolveContract(type);
        }

        #endregion
    }
}

配置应用:

var settings = new JsonSerializerSettings();
settings.ContractResolver = new SignalRContractResolver();
var serializer = JsonSerializer.Create(settings);
GlobalHost.DependencyResolver.Register(typeof (JsonSerializer), () => serializer);
var settings = new JsonSerializerSettings {ContractResolver = new SignalRContractResolver()};
var serializer = JsonSerializer.Create(settings);
builder.Register(c => serializer).As<JsonSerializer>();
阅读全文
公众号-介尘阅读时光
赞赏支持

0 Responses to “Automatic camel-casing of properties with SignalR hubs”

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

×