How can I create a custom snap module when binding to a body?

I tried to experiment with model binding to make it easier to use our API. When using the API, I cannot get the model binding for the binding when the data is in the body, only when it is part of the request.

The code I 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 you look at the ValueProvider property on a bindingContext , I see only QueryStringValueProvider and RouteDataValueProvider , which, I think, means that if the data is in the body, I will not receive it. How can I do it? I would like to support sending data as json or form-encoded.

+4
source share
1 answer

I also study this.

WebApis Model Binder comes with two built-in ValueProviders.

QueryStringValueProviderFactory and RouteDataValueProviderFactory

Which are executed when called

 context.ValueProvider.GetValue 

There is code in this question on how to associate data with the body.

how to pass a result model object from System.Web.Http.ModelBinding.IModelBinder. Bindmodel?

You can create your own ValueProvider to do this, perhaps the best idea is that as a result of the search, a value matching the key will be found. The above link just does it within the bounds of the model’s connecting device, which limits the ModelBinder to be viewed only in the body.

 public class FormBodyValueProvider : IValueProvider { private string body; public FormBodyValueProvider ( HttpActionContext actionContext ) { if ( actionContext == null ) { throw new ArgumentNullException( "actionContext" ); } //List out all Form Body Values body = actionContext.Request.Content.ReadAsStringAsync().Result; } 

// Implement the interface and use the code to read the body and find your value that matches your key}

0
source

All Articles