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

ASP.Net Web API 2 attribute-routed HTTP POST action not getting correct parameter

我有一个简单的 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 }
        );
    }
}

如果您使用 html formPOST 方法中的参数将不会立即反序列化。 Use the [FromBody] attribute得到msg的值。

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

否则,您必须使用 Fiddler(或类似的网络调试器)调用 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 ;
}