我有一个简单的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 }
);
}
}
POST
如果您使用的是html ,则方法中的参数将不会立即反序列化form
。使用该[FromBody]
属性获取的值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 ;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句