Nicros
Nicros

Reputation: 5193

Web.API and FromBody

I'm a bit confused. I have a controller (derived from ApiController) that has the following method:

[ActionName("getusername")]
public string GetUserName(string name)
{
    return "TestUser";
}

My routing is set up like this:

config.Routes.MapHttpRoute(
    name: "ActionApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

I kept getting a 400 error when I try to hit /api/mycontroller/getusername/test with a GET in fiddler.

I found that everything worked when I added [FromBody] to the name parameter in GetUserName.

I was somehow thinking that [FromBody] was used for HttpPost, signalling that the parameter was in the body of the post, and would therefore not be needed for a GET. Looks like I was wrong though.

How does this work?

Upvotes: 3

Views: 3532

Answers (2)

chrisjsherm
chrisjsherm

Reputation: 1329

You could also do the following if it is closer to what you were looking for:

// GET api/user?name=test
public string Get(string name)
{
    return "TestUser";
}

This assumes you are using an ApiController named UserController and allows you to pass your name parameter as a query string. This way, you don't have to specify the ActionMethod but rather rely on the HTTP verb and matching route.

Upvotes: 1

Christopher.Cubells
Christopher.Cubells

Reputation: 911

You need to either change your routing to:

config.Routes.MapHttpRoute(
    name: "ActionApi",
    routeTemplate: "api/{controller}/{action}/{name}",
    defaults: new { name = RouteParameter.Optional }
);

or change the name of your parameter to:

[ActionName("getusername")]
public string GetUserName(string id)
{
    return "TestUser";
}

Note: Additional routing parameters must match method parameter names.

Upvotes: 6

Related Questions