I want to send a HTTP POST request with the body containing information that makes up a simple blog post, nothing fancy.
I've read here that when you want to bind a complex type (i.e. a type that is not string
, int
etc) in Web API, a good approach is to create a custom model binder.
I have a custom model binder (BlogPostModelBinder
) that in turn uses a custom Value Provider (BlogPostValueProvider
). What I don't understand is that how and where shall I be able to retrieve the data from the request body in the BlogPostValueProvider
?
Inside the model binder this is what I thought would be the right way to for example retrieve the title.
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
...
var title= bindingContext.ValueProvider.GetValue("Title");
...
}
while the BlogPostValueProvider looks like this:
public class BlogPostValueProvider : IValueProvider
{
public BlogPostValueProvider(HttpActionContext actionContext)
{
// I can find request header information in the actionContext, but not the body.
}
public ValueProviderResult GetValue(string key)
{
// In some way return the value from the body with the given key.
}
}
This might be solvable in an easier way, but since i'm exploring Web API it would be nice to get it to work.
My problem is simply that I cannot find where the request body is stored.
Thanks for any guidance!
Content-Type
header and Media type formatters. When a request's content-type is formurlencoded,FormUrlEncodedMediaTypeFormatter
is handled the request body to do whatever it wants. Its in this process that theIModelBinder
&IValueProvider
come into picture whereas in case of json, it is handled byJsonMediaTypeFormatter
which in turn depends on let's say JSON.Net's deserializer. This deserialzer does not have the concept of modelbinders or value providers. – Kozhikode