asp.net - How do I do a custom modelbinder when binding from body? -
i've been trying experiment model binding make our api easier use. when using api can't model binding bind when data in body, when part of query.
the code have is:
public class funkymodelbinder : imodelbinder { public bool bindmodel(httpactioncontext actioncontext, modelbindingcontext bindingcontext) { var model = (funky) bindingcontext.model ?? new funky(); var hasprefix = bindingcontext.valueprovider .containsprefix(bindingcontext.modelname); var searchprefix = (hasprefix) ? bindingcontext.modelname + "." : ""; model.funk = getvalue(bindingcontext, searchprefix, "funk"); bindingcontext.model = model; return true; } private string getvalue(modelbindingcontext context, string prefix, string key) { var result = context.valueprovider.getvalue(prefix + key); return result == null ? null : result.attemptedvalue; } }
when looking @ valueprovider
property on bindingcontext
see querystringvalueprovider
, routedatavalueprovider
think means if data in body won't it. how should this? support posting data either json or form-encoded.
i looking well.
webapis model binder comes 2 built in valueproviders.
querystringvalueproviderfactory & routedatavalueproviderfactory
which searched when call
context.valueprovider.getvalue
this question has code on how bind data body.
how pass result model object out of system.web.http.modelbinding.imodelbinder. bindmodel?
you create custom valueprovider well, better idea - searched value matching key. above link within model binder, limits modelbinder looking in body.
public class formbodyvalueprovider : ivalueprovider { private string body; public formbodyvalueprovider ( httpactioncontext actioncontext ) { if ( actioncontext == null ) { throw new argumentnullexception( "actioncontext" ); } //list out form body values body = actioncontext.request.content.readasstringasync().result; }
//implement interface , use code read body , find value matching key }
Comments
Post a Comment