gpt4 book ai didi

asp.net-web-api - ASP.Net Web API 2 属性路由 HTTP POST 操作未获得正确的参数

转载 作者:行者123 更新时间:2023-12-03 23:25:01 26 4
gpt4 key购买 nike

我有一个简单的 ASP.Net Web API 2 Controller :

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参数在发布到 Controller 时是否已路由到操作?

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

以防万一 HTTP GET 分散注意力,此版本的 Controller 也无法接收正确的 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,方法将不会开箱即用地反序列化. 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 ;
}

关于asp.net-web-api - ASP.Net Web API 2 属性路由 HTTP POST 操作未获得正确的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28069577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com