Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 727
Nicros Avatar asked Aug 19 '26 15:08

Nicros


1 Answers

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.

like image 166
Christopher.Cubells Avatar answered Aug 24 '26 13:08

Christopher.Cubells



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!