David Kethel
David Kethel

Reputation: 2550

How do I get access to my requests content in a custom model binder in Asp Net MVC 4 Web Api?

I have been thinking about how I can solve the problem I had in my previous question

Can I get access to the data that the .net web api model binding was not able to handle?

I'm thing that I can use my own custom model binder, that way I can handle the perfect case , and write to a log when I get data that I wasn't expecting.

I have the following class and Model Binders

 public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class CustomPersonModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        var myPerson = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        var myPersonName = bindingContext.ValueProvider.GetValue("Name");

        var myId = bindingContext.ValueProvider.GetValue("Id");

        bindingContext.Model = new Person {Id = 2, Name = "dave"};
        return true;
    }
}

public class CustomPersonModelBinderProvider : ModelBinderProvider
{
    private  CustomPersonModelBinder _customPersonModelBinder = new CustomPersonModelBinder();

    public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)
    {
        if (modelType == typeof (Person))
        {
            return _customPersonModelBinder;
        }
        return null;
    }
}

and here is my controller method

   public HttpResponseMessage Post([ModelBinder(typeof(CustomPersonModelBinderProvider))]Person person)
    {
        return new HttpResponseMessage(HttpStatusCode.OK);
    }

And I have been invoking it using fiddler with

Post http://localhost:18475/00.00.001/trial/343

{  
        "Id": 31,
        "Name": "Camera Broken"
}

This works great, Without using the custom model binder I get a Person object populated from my json data in my post method, and with the custom model binder I always get a person(Id= 2, Name = "dave").

The problem is I can't seem to get access to the JSon data in my custom Model binder.

The myPerson and myPersonName variables in the bindModel method are both null. however the myId variable is populated with 343.

Any Ideas how I can get access to the data in the json within my BindModel method?

Upvotes: 2

Views: 1362

Answers (1)

Sando
Sando

Reputation: 667

Try this:

actionContext.Request.Content.ReadAsStreamAsync()

Upvotes: 2

Related Questions