71

I'm trying to get a post request to work with the web api. Following is my api controller.

public class WebsController : ApiController
{
    [HttpPost]
    public void PostOne(string id)
    {
    }

    [HttpPost]
    public void PostTwo(Temp id)
    {
    }
}

I have altered the webapi route to take the action into account. the Temp model look something like this.

public class Temp
{
    public string Id { get; set; }
}

my view look something like this

@using (Ajax.BeginForm(new AjaxOptions
{
    Url = "/api/webs/postone",
    HttpMethod = "post"
}))
{
    <input name="id" id="id" value="2" />
    <input type="submit" value="submit" />
}

the above code does not work at all with the postone unless I put the [FromBody] attribute in front of the parameter like this.

[HttpPost]
public void PostOne([FromBody]string id)
{
}

then it hits the action, but the id is still null. It doesn't get populated with the value in the textbox.

But, if I change the Url of the Ajax.BeginForm to posttwo which take the model Temp, it works nicely and the Id field gets the proper value in the textbox.

can anyone please explain me the reason for this to happen and how I can post a simple value to a web api action? I mean, why can it bind a complex type but not a simple type.

4

1 回答 1

112

自从我问这个问题以来已经有一段时间了。现在我更清楚地了解它,我将提供更完整的答案以帮助其他人。

在 Web API 中,记住参数绑定是如何发生的非常简单。

  • 如果您使用POST简单类型,Web API 会尝试从 URL 绑定它
  • 如果您POST输入复杂类型,Web API 会尝试从请求正文中绑定它(这使用media-type格式化程序)。

  • 如果您想从 URL 绑定复杂类型,您将[FromUri]在您的操作参数中使用。这样做的限制取决于您的数据将持续多长时间以及它是否超过了 url 字符限制。

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • 如果您想从请求正文中绑定一个简单类型,您将在您的操作参数中使用 [FromBody]。

    public IHttpActionResult Put([FromBody] string name) { ... }

作为旁注,假设您正在发出PUT请求(只是一个字符串)来更新某些内容。如果您决定不将其附加到 URL 并作为模型中只有一个属性的复杂类型传递,那么datajQuery ajax 中的参数将如下所示。您传递给 data 参数的对象只有一个属性名称为空的属性。

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

您的 Web api 操作将如下所示。

public IHttpActionResult Put([FromBody] string name){ ... }

这个 asp.net 页面解释了这一切。 http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

于 2015-11-12T08:50:48.513 回答