【问题标题】:Using Postman to test POST with .net core 2.1使用 Postman 使用 .net core 2.1 测试 POST
【发布时间】:2019-02-19 01:18:47
【问题描述】:

我正在测试一个新的 .net 应用程序,该应用程序将使用 JWT 创建用于站点访问的令牌。我有一个简单的模型:

    namespace JWTAuth.Entities
{
    public class User
    {
        public int id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string Token { get; set; }
    }
}

我现在有一个简单的控制器,可以接受 POST:

    namespace JWTAuth.Controllers
{
    [Authorize]

    [Route("api/[controller]")]
    [ApiController]
    public class UsersController : ControllerBase
    {
        private IUserService _userService;

        public UsersController(IUserService userService)
        {
            _userService = userService;
        }
        [AllowAnonymous]
        [HttpPost("authenticate")]
        public IActionResult Authenticate([FromBody]User userParam)
        {
            var user = _userService.Authenticate(userParam.UserName, userParam.Password);
            if (user == null)
                return BadRequest(new { message = "Username or password incorrect." });

            return Ok(User);
        }
        [HttpGet]
        public IActionResult GetAll()
        {
            var users = _userService.GetAll();
            return Ok(users);
        }
    }
}

当我使用邮递员时,我使用的是 POST 方法,正文中包含以下原始 JSON:

    {
  "id": 0,
  "firstName": null,
  "lastName": null,
  "userName": "test",
  "password": "user",
  "token": null
}

当我在构造函数上设置断点时,我会很好地进入构造函数,但是当我去 POST 时,我会不断获取数据:

{
    "": [
        "The input was not valid."
    ]
}

我点击的网址是: https://localhost:44378/api/users/authenticate

我已尝试在 JSON 中进行各种更改以发布此内容,但我无法克服此错误。我在 stackoverflow 和 Google 中四处寻找解决方案,但我被卡住了。

【问题讨论】:

    标签: asp.net-core jwt


    【解决方案1】:

    选择JSON (application/json)的正文内容类型

    或手动将Content-Type 标头设置为application/json

    【讨论】:

    • 宾果游戏!谢谢。设置 JSON(application/json) 解决了这个问题。谢谢。
    猜你喜欢
    • 2019-02-11
    • 2019-03-20
    • 2021-05-29
    • 2021-07-23
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 2020-10-15
    • 2018-04-04
    相关资源
    最近更新 更多