Objectid serialization and deserialization of MVC when using MongoDB

Source: Internet
Author: User
Tags httpcontext serialization

The previous write using your own MVC serialization tool is Jsonnetresult. I'm going to do a JSON serialization tool with the previously written Jsonnetresult, and serialize Objectid into a string. The specific code is as follows

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 {Reference        loophandling = 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 Js                Onserializersettings (); _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 Invalidoperationexcep            tion ("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 ()); }        }    }}


Add a line of code to Jsonnetresult:

_settings. Converters.add (New Objectidconverter ());

Our objectidconverter is specifically implemented as follows:

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);}}}    
This jsonnetresult has the ability to serialize Objectid types of data. Of course, other things that have special needs sequences are implemented in a similar way.

Serialization is complete, followed by deserialization, if the Objectid string is not processed, the Objectid object becomes objectid.empt (that is, all 00), or it is received using a string, but this is not what we want to see.

We use MVC Modelbinder to implement Objectid object deserialization

The specific code is as follows:

Add Reference

Using system;using system.web.mvc;using Mongodb.bson;

Code implementation:

public class Objectidmodelbinder:imodelbinder {public Object Bindmodel (ControllerContext controllercontext, M                Odelbindingcontext 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 VA                Lue 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 registration, add the following code to the Global.asax file Application_Start method:

MODELBINDERPROVIDERS.BINDERPROVIDERS.ADD (New Objectidprovider ());
So Objectid deserialization is done, is not very simple, hehe.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.