设置 POST Web API 方法?
Setting up a POST Web API Method?
我需要设置 Web API 方法来接受从我的 Android 和 iOS 客户端应用程序发送的 POST 参数。这就是我现在拥有的:
[HttpPost]
[Route("api/postcomment")]
public IHttpActionResult PostComment([FromBody]string comment, [FromBody]string email, [FromBody]string actid)
{
string status = CommentClass.PostNewComment(comment, email, actid);
return Ok(status);
}
但是这行不通,因为我认为该方法不能同时获取多个 [FromBody] 参数?如何正确设置此方法,使其从请求正文中接受 3 个 POST 参数?
您可以使用模型。 DefaultModelBinder 会将 表单 中的那些值绑定到您的模型。
public class CommentViewModel
{
public string Comment { get; set; }
public string Email { get; set; }
public string Actid { get; set; }
}
public IHttpActionResult PostComment([FromBody]CommentViewModel model)
{
string status = ...;
return Ok(status);
}
你可以这样做 -
- Create one custom class and add three properties for your three input parameters.
- Change the
PostComment
method to accept only one parameters of that class.
- While calling this WebAPI, create one object of this class, assign values to the properties, serialize it to JSON or XML and POST it.
- The WebAPI will automatically de-serialize your Request Body and pass it to your method.
我需要设置 Web API 方法来接受从我的 Android 和 iOS 客户端应用程序发送的 POST 参数。这就是我现在拥有的:
[HttpPost]
[Route("api/postcomment")]
public IHttpActionResult PostComment([FromBody]string comment, [FromBody]string email, [FromBody]string actid)
{
string status = CommentClass.PostNewComment(comment, email, actid);
return Ok(status);
}
但是这行不通,因为我认为该方法不能同时获取多个 [FromBody] 参数?如何正确设置此方法,使其从请求正文中接受 3 个 POST 参数?
您可以使用模型。 DefaultModelBinder 会将 表单 中的那些值绑定到您的模型。
public class CommentViewModel
{
public string Comment { get; set; }
public string Email { get; set; }
public string Actid { get; set; }
}
public IHttpActionResult PostComment([FromBody]CommentViewModel model)
{
string status = ...;
return Ok(status);
}
你可以这样做 -
- Create one custom class and add three properties for your three input parameters.
- Change the
PostComment
method to accept only one parameters of that class.- While calling this WebAPI, create one object of this class, assign values to the properties, serialize it to JSON or XML and POST it.
- The WebAPI will automatically de-serialize your Request Body and pass it to your method.