c# - 同时使用 [FromUri] 和 [FromBody] 绑定(bind)复杂的 Web Api 方法参数

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

我使用请求和响应模型来封装需要传递给我的 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],同时保持所有参数都在一个对象中。这可能吗?

最佳答案

不是最干净的解决方案,但它应该有效:

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

关于c# - 同时使用 [FromUri] 和 [FromBody] 绑定(bind)复杂的 Web Api 方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32066063/

相关文章:

c# - 将构造函数与泛型类型定义中的对应项匹配

c# - 将生成的pdf直接保存到服务器目录文件夹中,无需用户提示

jquery - 如何显示基于 Html.DropDownList 的 div?

asp.net - Winforms、ASP.NET、WPF 的语法高亮文本框

c# - Web API 和取消 token

javascript - 删除#!来自 ASP.Net Web API 中的 angular.js URL

c# - 在 Visual Studio C# 中,有没有办法将 Web Config 转换应用于 Javascript 文件?

c# - 如何使用 MVVM 模式创建和组织非 UI 相关元素

c# - A/B 测试又称为拆分测试

c# - Asp.Net Web Api 2 中的 If-Modified-Since