ASP.Net Web API 2属性路由HTTP POST操作未获取正确的参数

时间:2015-01-21 14:26:42

标签: asp.net-web-api asp.net-web-api2 asp.net-web-api-routing

我有一个简单的ASP.Net Web API 2控制器:

public class TestController : ApiController
{
    [Route("api/method/{msg?}")]
    [AcceptVerbs("GET", "POST")]
    public string Method(string msg = "John")
    {
        return "hello " + msg;
    }
}

一个简单的HTML表单来测试它。

<form action="/api/method/" method="post">
    <input type="text" name="msg" value="Tim" />
    <input type="submit" />
</form>

当我加载页面并提交表单时,生成的字符串为"hello John"。如果我将表单的方法从post更改为get,结果将更改为"hello Tim"。为什么在将msg参数发布到控制器时未将其路由到操作?

==========编辑1 ==========

如果HTTP GET分散注意力,这个版本的控制器也无法从发布的表单中接收到正确的msg参数:

[Route("api/method/{msg?}")]
[HttpPost]
public string Method(string msg = "John")
{
    return "hello " + msg;
}

==========编辑2 ==========

我没有更改默认路由,因此它仍然如下所示:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

1 个答案:

答案 0 :(得分:4)

如果您使用的是html POST,则form方法中的参数不会被反序列化。 Use the [FromBody] attribute获取msg的值。

[HttpPost]
[Route("api/method")]
public string Method([FromBody] string msg)
{
    return "hello " + msg;
}

否则,您必须使用Fiddler(或类似的Web调试器)来调用POST方法并将msg作为查询字符串传递。

如果您真的想在不使用HTML Form属性的情况下使用[FromBody],请尝试以下

[HttpPost]
[Route("api/method")]
public string Method()
{
    var msg = Request.Content.ReadAsFormDataAsync();
    var res= msg.Result["msg"];
    return "hello " + res ;
}