Question

I have an action in my Web API project that accepts a view model object like this:

public string Blah(Foo model)

Foo looks like this:

public class Foo
{
    public string Bar { get; set; }
}

(The reason I'm using a view model class rather than binding Bar directly as a string is because I want to plug the class into some validation logic.)

My routing looks like this:

config.Routes.MapHttpRoute(
                name: "Name",
                routeTemplate: "Blah/{Bar}",
                defaults: new { controller = "MyController", action = "Blah", Bar = RouteParameter.Optional });

What I'm finding is that calling the endpoint hits the action method, but the Foo view model is null. I was expecting a hydrated Foo with the Bar property set to whatever the user had supplied in the URL. I thought this kind of property binding worked out of the box with MVC?

Can anyone point out what I've done wrong?

Was it helpful?

Solution

So Web API assumes that GET requests will use simple types in the action method signature, and POST etc will use complex types.

GET requests by default will not bind complex types from values in the URL. To enable this, you add a special attribute:

public string Blah([FromUri]Foo model)

Then everything works as expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top