【问题标题】:Simple controller which takes POST is not found未找到需要 POST 的简单控制器
【发布时间】:2012-08-27 13:26:00
【问题描述】:

自从我将 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'."
}

为什么找不到 POST 控制器?

控制器

public class PlayController : ApiController
{
    [HttpPost]  // not found
    public string Test(string output)
    {
        return output;
    }

    [HttpGet]  // works
    public string Test2(string output)
    {
        return output;
    }
}

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>

【问题讨论】:

    标签: asp.net-mvc-4 asp.net-web-api forms


    【解决方案1】:

    当您想要发布“简单”值时,Web.API 有点挑剔。

    您需要使用[FromBody] 属性来表明该值不是来自 URL 而是来自发布的数据:

    [HttpPost]
    public string Test([FromBody] string output)
    {
        return output;
    }
    

    通过此更改,您将不再获得 404,但 output 将始终为空,因为 Web.Api 需要在 special format 中发布的值(查找“发送简单类型”部分):

    其次,客户端需要发送如下格式的值:

    =value

    具体来说,对于简单类型,名称/值对的名称部分必须为空。并非>所有浏览器都支持 HTML 表单, 但是您在脚本中创建这种格式...

    所以建议你应该创建一个模型类型:

    public class MyModel
    {
        public string Output { get; set; }
    }
    
    [HttpPost]
    public string Test(MyModel model)
    {
        return model.Output;
    }
    

    然后它将与您的示例一起使用,而无需修改您的视图。

    【讨论】:

    • 如果我能在 3 年后加入,谢谢!!这解决了我刚刚花了几个小时解决的问题。这正是 SO 的全部意义所在。
    • 当我在 webApiConfig.cs 和控制器中的过程之间存在参数名称不匹配时,我得到了同样的错误。
    猜你喜欢
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 2013-10-04
    • 2013-04-20
    • 1970-01-01
    • 2023-03-30
    • 2015-07-07
    • 1970-01-01
    相关资源
    最近更新 更多