【问题标题】:Using [FromUri] and [FromBody] simultaneously to bind a complex Web Api method parameter同时使用 [FromUri] 和 [FromBody] 绑定复杂的 Web Api 方法参数
【发布时间】:2015-11-11 00:22:09
【问题描述】:

我正在使用请求和响应模型来封装需要传递给我的 ASP.NET Web Api 中的方法的数据,必要时使用 [FromUri][FromBody]

但是,在某些情况下,我想同时使用 Uri 和 Body 来填充我的请求模型的属性。一个例子是更新用户,UserId 应该在 Uri 中传递,但要更新的数据将在正文内容中传递。我想要的实现看起来像这样:

型号

public class UpdateUserRequestModel
{
    public string UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string DisplayName { get; set; }
}

API 方法

[HttpPut]
[Route("Update/{UserId}")]
// PUT: api/Users/Update/user@domain.net
public async Task UpdateUserAsync(UpdateUserRequestModel model)
{
    // Method logic
}

我希望获得UserId 的属性[FromUri],但要获得其余的[FromBody],同时将所有参数都保存在一个对象中。这可能吗?

【问题讨论】:

  • 我不知道这是否可能,但如果不是,您可以随时编写自己的自定义序列化程序。
  • A HTTPPUT 允许这样做。但是您需要同时传递 uri 参数和 body
  • @AmitKumarGhosh 我将如何设计我的语法来支持它?请记住,我正在尝试填充来自不同来源的单个输入参数的属性。
  • 在您的操作中接受两个参数,通过uri 传递id 属性,并通过body 传递整个对象。
  • @AmitKumarGhosh 我目前在我的代码中使用这种方法。我想要做的是保持该级别的功能,但转移id 属性并将其放入model 参数中,

标签: c# asp.net asp.net-web-api dto asp.net-web-api-routing


【解决方案1】:

不是最干净的解决方案,但它应该可以工作:

[HttpPut]
[Route("Update/{UserId}")]
// PUT: api/Users/Update/user@domain.net
public async Task UpdateUserAsync(UpdateUserRequestModel model, int UserId)
{
    model.UserId = UserId;
}

【讨论】:

    猜你喜欢
    • 2019-06-09
    • 1970-01-01
    • 2012-08-17
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    相关资源
    最近更新 更多