【问题标题】:Restful MVC API action requires URL parameters on POSTRestful MVC API 操作需要 POST 上的 URL 参数
【发布时间】:2014-06-05 19:35:10
【问题描述】:

在控制器中,我有这样的方法:

public class FooController : ApiController
{
    [HttpPost]
    public HttpResponseMessage ApplySomething(int id)
    {
        ...
    }
}

当我执行 .../Foo/ApplySomething/ 之类的 POST 请求并将 id=1 作为 POST 值传递时,出现错误:

{
    Message: "No HTTP resource was found that matches the request URI '.../Foo/ApplySomething/'."
    MessageDetail: "No action was found on the controller 'Foo' that matches the name 'ApplySomething'."
}

但是当我将 URL 更改为具有 ID(如 .../Foo/ApplySomething/1)时,它可以工作,但从 URL 获取值,而不是从 POST 值。

我做错了什么?

【问题讨论】:

  • /Foo/ApplySomething?id=1 有效吗?
  • 是的,/Foo/ApplySomething?id=1 和 /Foo/ApplySomething/1 的工作方式相同。

标签: c# .net asp.net-mvc restful-url


【解决方案1】:

默认情况下,Web API 使用以下规则绑定参数:

  • 如果参数是“简单”类型,Web API 会尝试从 URI 中获取值。简单类型包括 .NET 基本类型(int、bool、double 等),加上 TimeSpan、DateTime、Guid、decimal 和 string,以及任何具有可以从字符串转换的类型转换器的类型。 (稍后会详细介绍类型转换器。)
  • 对于复杂类型,Web API 尝试使用 media-type formatter 从消息正文中读取值。

鉴于这些规则,如果您想绑定 POST 正文中的参数,只需在类型前添加 [FromBody] 属性:

public HttpResponseMessage ApplySomething([FromBody] int id) { ... }

欲了解更多信息please see the documentation

【讨论】:

  • 在我看来,当我使用 FromBody 时,整个内容都绑定到单个参数,而不是使用 'id=1&anotherParam=value' 格式,对吗?
  • 你的问题没有提到任何其他参数,所以这取决于你需要做什么。如果您需要多个参数,我只会构建一个复杂类型(例如某个模型类)并将所有需要的参数作为属性。默认情况下,框架将绑定到该类型,您就可以开始了。不过,没有什么能阻止您同时使用 ([FromBody] int id, YourModel model) 作为方法签名。
  • 是的,确切地说,如果您想将其解析为单独的字段,您可以使用其他类型的字段 'FormDataCollection' 而不是 int
【解决方案2】:

试试这个:

public class FooController : ApiController
{
    [HttpGet]
    public HttpResponseMessage ApplySomething(int? id=0)
    {
        ...
       return View();    
    }
    [HttpPost]
    public HttpResponseMessage ApplySomething(FormCollection Form,int? id=0)
    {
        ...
       return View();    
    }
}

现在试试这个网址.../Foo/ApplySomething?id=1

希望它有效...!

【讨论】:

    【解决方案3】:
    猜你喜欢
    • 2018-06-17
    • 2016-06-14
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多