Web.API and FromBody

I am 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 400 error when I try to push /api/mycontroller/getusername/test

with GET in fiddler.

I found that everything worked when I added [FromBody]

the name parameter to GetUserName.

I somehow thought what was [FromBody]

used for HttpPost

, signaling that the parameter was in the body of the message, and therefore not needed for GET

. Looks like I was wrong though.

How it works?

+3


source to share


2 answers


You either need to change your routing or:

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 the method parameter names.

+6


source


You can also do the following if it's closer to what you were looking for:

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

      



This assumes you are using ApiController

with a name UserController

and can pass your parameter name

as a query string. This way you don't need to specify ActionMethod

, but rather rely on the HTTP verb and the corresponding route.

+1


source







All Articles