mvc使用mongodb時objectId序列化與還原序列化

來源:互聯網
上載者:User

標籤:mvc objectid   objectid序列化   objectid還原序列化   mvc mongodb   

前面有寫使用自己的mvc 序列化工具即jsonNetResult。我這裡結合之前寫的jsonNetResult來做一個Json序列化工具,並且序列化ObjectId成一個字串。具體代碼如下

using System;using System.IO;using System.Text;using System.Web.Mvc;using Aft.Build.Common;using Newtonsoft.Json;using Newtonsoft.Json.Serialization;namespace Aft.Build.MvcWeb.Common{    public class JsonNetResult : JsonResult    {        public JsonNetResult()        {            Settings = new JsonSerializerSettings            {                ReferenceLoopHandling = ReferenceLoopHandling.Error            };        }        public JsonNetResult(object data, JsonRequestBehavior behavior = JsonRequestBehavior.AllowGet, string contentType = null, Encoding contentEncoding = null)        {            Data = data;            JsonRequestBehavior = behavior;            ContentEncoding = contentEncoding;            ContentType = contentType;        }        private JsonSerializerSettings _settings;        public JsonSerializerSettings Settings        {            get            {                _settings = _settings ?? new JsonSerializerSettings();                _settings.ContractResolver = new CamelCasePropertyNamesContractResolver();                _settings.Converters.Add(new ObjectIdConverter());                return _settings;            }            private set { _settings = value; }        }        public override void ExecuteResult(ControllerContext context)        {            if (context == null)                throw new ArgumentNullException("context");            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))                throw new InvalidOperationException("JSON GET is not allowed");            var response = context.HttpContext.Response;            response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/json" : ContentType;            if (ContentEncoding != null)                response.ContentEncoding = ContentEncoding;            if (Data == null)                return;            var scriptSerializer = JsonSerializer.Create(Settings);            using (var sw = new StringWriter())            {                scriptSerializer.Serialize(sw, Data);                response.Write(sw.ToString());            }        }    }}


在jsonnetresult添加一行代碼:

_settings.Converters.Add(new ObjectIdConverter());

我們的ObjectIdConverter具體實現如下:

using System;using MongoDB.Bson;using Newtonsoft.Json;namespace Aft.Build.Common{    public class ObjectIdConverter : JsonConverter    {        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)        {            serializer.Serialize(writer, value.ToString());        }        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)        {            ObjectId result;            ObjectId.TryParse(reader.Value as string, out result);            return result;        }        public override bool CanConvert(Type objectType)        {            return typeof(ObjectId).IsAssignableFrom(objectType);        }    }}
這樣JsonNetResult就具備可以序列化ObjectId類型的資料了。當然其他有特殊需要序列的話的東西實現方式類同。

序列化完成了,接下來是還原序列化,如果不經處理Objectid字串是沒有辦法反序列ObjectId對象的會變成Objectid.empt(即全是零0),或者是使用字串來接收,但是這不是我們希望看到的。

我們使用mvc ModelBinder 來實現ObjectId對象的還原序列化

具體代碼如下:

添加引用

using System;using System.Web.Mvc;using MongoDB.Bson;

代碼實現:

public class ObjectIdModelBinder : IModelBinder    {        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)        {            if (bindingContext.ModelType != typeof(ObjectId))            {                return ObjectId.Empty;            }            var val = bindingContext.ValueProvider.GetValue(                bindingContext.ModelName);            if (val == null)            {                return ObjectId.Empty;            }            var value = val.AttemptedValue;            if (value == null)            {                bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Wrong value type");                return ObjectId.Empty;            }            ObjectId result;            if (ObjectId.TryParse(value, out result))            {                return result;            }            return ObjectId.Empty;        }    }    public class ObjectIdProvider : IModelBinderProvider    {        public IModelBinder GetBinder(Type modelType)        {            if (modelType == typeof(ObjectId) || modelType == typeof(ObjectId?))            {                return new ObjectIdModelBinder();            }            return null;        }    }


全域註冊,在Global.asax檔案Application_Start方法中添加如下代碼:

ModelBinderProviders.BinderProviders.Add(new ObjectIdProvider());
這樣ObjectId還原序列化就做好了,是不是很簡單,呵呵。



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.