c# - WebApi 获取和发布的不同 DTO

标签 c# asp.net-web-api

GET 和 POST 操作可以使用不同的 DTO 吗?

原因是这两种数据模型之间通常存在巨大差异。

例如:

我的帖子看起来像这样:

/// <summary>
/// Add new user
/// </summary>
/// <param name="item">User data</param>
/// <returns>Newly added user id</returns>
[HttpPost]
public IHttpActionResult Post([FromBody] UserDto item)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var model = _mapper.Map<User>(item);

    int itemid = _usersRepository.Insert(model);

    return Ok(itemid);
}

public class UserDto
{
    private string _password;

    [Required]
    [StringLength(100, ErrorMessage = "Name {0} must consist of at least {2} letters.", MinimumLength = 6)]
    public string Name { get; set; }

    [Required]
    public string ExternalName { get; set; }

    [Required]
    public bool Active { get; set; }

    [Required]
    public string Password
    {
        get { return _password; }
        set { _password = value.Hash(); }
    }
}

我的 GET 看起来像这样:

/// <summary>
/// Get all users
/// </summary>
/// <returns>Users list</returns>
[HttpGet]
[ResponseType(typeof(List<UserInfoDto>))]
public IHttpActionResult Get()
{
    IList<UserInfoDto> values = _usersRepository.SelectAll();

    if (values == null || !values.Any())
        return Ok();

    return Json(new { collection = values });
}

public class UserInfoDto
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string ExternalName { get; set; }

    public bool Active { get; set; }
}

我这样做的原因是我在发布资源时不需要 Id,但需要密码。使用 GET 时相反。

这是使用 WebApi 时的正确方法吗(为响应和请求创建不同的 Dto)?还是有其他方法可以做到这一点?

最佳答案

Is it ok to have different DTO's for GET and POST actions ?

对不同的操作使用不同的 dto 没有错。

如果 api 被第 3 方使用,您需要确保它有完整的文档。

Is this the correct approach when using WebApi?

这是否是正确的方法是一个见仁见智的问题。公开或接受系统按预期运行所需的信息。

每个 Action 都可以使用自己独特的 dto。并不意味着它应该。您要确保不会泄露不必要的信息。

关于c# - WebApi 获取和发布的不同 DTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41427075/

相关文章:

c# - 用 Java 构建的基于 Spring 的代理的 Stomp WebSocket 客户端失败

c# - 在 C# 中使用 XML 作为列表结构的设计模式

asp.net - 2. 如何处理 WebAPI 方法中的异常?

asp.net-mvc - ASP .Net MVC 中多个设备的多 View

c# - 错误 500 "Queries cannot be applied to the response content of type ' System.Net.Http.ByteArrayContent'

c# - 具有相同路由前缀 ASP.NET Web Api 的多个 Controller 类型

c# - MVC - 多态 View 绑定(bind)可能吗?

c# - 为什么出现错误 "' CalendarsRequestBuilder' 不包含 'Request' “graphClient.Me.Calendars.Request().GetAsync(); 的定义;

c# - 如何从 ViewModel 读取 TextBox 焦点 - MVVM Light

c# - ASP.NET Web API 十进制验证