Web.API和FromBody

Nic*_*ros 3 asp.net-mvc-4 asp.net-web-api

我有点困惑.我有一个控制器(派生自ApiController)具有以下方法:

[ActionName("getusername")]
public string GetUserName(string name)
{
    return "TestUser";
}
Run Code Online (Sandbox Code Playgroud)

我的路由设置如下:

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

当我尝试/api/mycontroller/getusername/test在提琴手中使用GET 时,我一直遇到400错误.

我发现当我添加[FromBody]到GetUserName中的name参数时,一切都有效.

我在某种程度上认为这[FromBody]是用于HttpPost,表明参数是在帖子的主体,因此不需要GET.看起来我错了.

这是如何运作的?

Chr*_*lls 6

您需要将路由更改为:

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

或将参数名称更改为:

[ActionName("getusername")]
public string GetUserName(string id)
{
    return "TestUser";
}
Run Code Online (Sandbox Code Playgroud)

注意:其他路由参数必须与方法参数名称匹配.