sta*_*orn 44 forms asp.net-mvc-4 asp.net-web-api
自从我将MVC4 webapi beta更新为RC以来,我已经提出了一些问题,要求帮助解决问题.我现在得到了最多的顺序,但这里有一个我无法弄清楚原因.
对于这个简单的控制器,我有一个接受POST和一个接受GET的控制器.当我尝试通过从HTML表单发送请求来运行它们时,只找到GET控制器,而POST将返回以下错误.
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost/webapi/api/play/test'.",
"MessageDetail": "No action was found on the controller 'Play' that matches the name 'test'."
}
Run Code Online (Sandbox Code Playgroud)
为什么找不到POST控制器?
控制器
public class PlayController : ApiController
{
[HttpPost] // not found
public string Test(string output)
{
return output;
}
[HttpGet] // works
public string Test2(string output)
{
return output;
}
}
Run Code Online (Sandbox Code Playgroud)
HTML表单
<form action="http://localhost/webapi/api/play/test" method="post">
<input type="text" name="output" />
<input type="submit" name="submit" />
</form>
<form action="http://localhost/webapi/api/play/test2" method="get">
<input type="text" name="output" />
<input type="submit" name="submit" />
</form>
Run Code Online (Sandbox Code Playgroud)
nem*_*esv 93
当你想发布"简单"的值时,Web.API有点挑剔.
您需要使用该[FromBody]属性来表示该值不是来自URL而是来自发布的数据:
[HttpPost]
public string Test([FromBody] string output)
{
return output;
}
Run Code Online (Sandbox Code Playgroud)
通过此更改,您将不再获得404,但output将始终为null,因为Web.Api需要特殊格式的已发布值(查找"发送简单类型"部分):
其次,客户端需要使用以下格式发送值:
=value具体而言,对于简单类型,名称/值对的名称部分必须为空.不是>所有浏览器都支持HTML表单,但是你在脚本中创建了这种格式......
因此,建议您创建模型类型:
public class MyModel
{
public string Output { get; set; }
}
[HttpPost]
public string Test(MyModel model)
{
return model.Output;
}
Run Code Online (Sandbox Code Playgroud)
然后它将与您的样本一起使用,而无需修改您的视图.
| 归档时间: |
|
| 查看次数: |
23878 次 |
| 最近记录: |