c# - Custom Model Binder for a base class in Web API -


given following models

public class requestbase {     public datetime transactiontimestamp { get; set; }      public guid requestmessageid { get; set; }  }   [modelbinder(typeof(requestbasemodelbinder))] public class standardrequest : requestbase {       public guid myguidid { get; set; }      public int myintid { get; set; }  } 

the values in requestbase sent via headers i'm trying implement custom model binder bind them model

this i've got far

 public class requestbasemodelbinder :imodelbinder {     public bool bindmodel(httpactioncontext actioncontext, modelbindingcontext bindingcontext)     {         var requestbase = bindingcontext.model requestbase;          if (requestbase != null)         {             requestbase.requestmessageid =                guid.parse(actioncontext.request.headers.getvalues("requestmessageid").firstordefault());              requestbase.transactiontimestamp =                datetime.parse(actioncontext.request.headers.getvalues("transactiontimestamp").firstordefault());              return true;         }          return false;     } } 

it not working @ moment bindingcontext.model null

no, bindingcontext.model object action parameter.

you should headers actioncontext.request, build model ,and set model bindingcontext.model

code should like:

dictionary<string, string> kvps = new dictionary<string, string>();         if (!string.isnullorempty(actioncontext.request.requesturi.query))         {             kvps = actioncontext.request.getquerynamevaluepairs().todictionary(a=>a.key,a=>a.value);         }         //check , source data body          else if (actioncontext.request.content.isformdata())         {             var bodystring = actioncontext.request.content.readasstringasync().result;             try             {                 kvps = converttokvps(bodystring);             }             catch (exception ex)             {                 bindingcontext.modelstate.addmodelerror(bindingcontext.modelname, ex.message);                 return false;             }         }         else         {             bindingcontext.modelstate.addmodelerror(bindingcontext.modelname, "no input data");             return false;         }         object obj = null;          try         {             obj = new something(kvps);//build object key value pairs         }         catch (exception ex)         {             bindingcontext.modelstate.addmodelerror(                 bindingcontext.modelname, ex.message);             return false;         }          bindingcontext.model = obj;         return true; 

see example: http://www.codeproject.com/articles/701182/a-custom-model-binder-for-passing-complex-objects


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -