【问题标题】:Using HttpPost with DTO, postman is not able to invoke tht method使用带有 DTO 的 HttpPost,邮递员无法调用 tht 方法
【发布时间】:2021-07-19 05:24:58
【问题描述】:

下面是我尝试将输入作为 DTo 传递的 HttpPost 方法

[HttpPost("register")]
    public async Task<ActionResult<AppUser>> Register(RegisterDto registerDto)
    {
        if (await UserExists(registerDto.Username)) return BadRequest("Username is taken");

        using var hmac = new HMACSHA512();
        var user = new AppUser
        {
            UserName = registerDto.Username.ToLower(),
            //UserName = username,
            PasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(registerDto.Password)),
            //PasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password)),
            PasswordSalt = hmac.Key
        };
        _context.Users.Add(user);
        await _context.SaveChangesAsync();

        return user;
    }

}

这是我创建的 Dto 类,我在 HttpPost 方法中传递了它

注册 Dto 类:-

public class RegisterDto
{
    public string Username { get; set; }
    public string Password { get; set; }
}

当我尝试在 postman 中测试此方法时,它会抛出错误为 415 unsupported media type ,请查看下图。 邮递员错误:-

enter image description here

【问题讨论】:

  • 您必须通过正文而不是查询字符串传递参数

标签: c# asp.net-core-5.0


【解决方案1】:

您可能希望使用 JSON 属性装饰您的 DTO,使其看起来像这样:

public class RegisterDto
{
    [JsonProperty("username")]
    public string Username { get; set; }
    [JsonProperty("password")]
    public string Password { get; set; }
}

然后在您的 JSON 帖子中为数据使用匹配的大小写

{
   "username":"jane@doe.com",
   "password":"somethingsecure"
}

【讨论】:

    【解决方案2】:

    对不起,我的坏事,

    我需要在邮递员中选择内容类型为json,之前是纯文本,所以它会抛出错误。

    如何在 postman 中将 content-type 设置为 JSON (application/json)。

    转到您的 POST 请求中的正文,在那里您会找到原始选项。

    在它旁边,会有一个下拉菜单,选择JSON(application.json)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 2015-05-24
      • 1970-01-01
      • 2021-07-31
      • 1970-01-01
      相关资源
      最近更新 更多