【问题标题】:How can I change the parameter name in the request body?如何更改请求正文中的参数名称?
【发布时间】:2019-02-18 11:55:27
【问题描述】:

我有这个模型'LoginModel'。

public class LoginModel
{
    public string UserName { get; set; }
    public string Pssd { get; set; }
}

我在控制器上使用这个类,然后像这样从主体中获取值。

public object CheckLogin([FromBody]LoginModel logModel){}

所以为了能够获得值,我必须将其放入请求中。

{
  "UserName": "username",
  "Pssd": "password"
}

我希望参数“Pssd”为“Password”,同时保留 Pssd 作为其方法名称。我已经尝试过使用这些属性,但它仍然不起作用。当我在请求正文中将 Pssd 替换为 Password 时,它的值变为 null。

    [JsonProperty("Password")]
    [JsonProperty(PropertyName = "Password")]
    [Display(Name = "Password")]
    [DataMember(Name = "Password")]

我也试过删除 [FromBody],但还是不行。

【问题讨论】:

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


    【解决方案1】:

    你试过[BindProperty(Name ="password")] 吗?

    或尝试使用简单的字母“密码”[JsonProperty(PropertyName = "password")]

    工作样本。

    [Route("test")]
    [HttpPost]
    public IActionResult Login([FromBody]LoginDto x)
    {
        return Ok(x);
    }
    
    public class LoginDto
    {
    
        public string UserName { get; set; }
        [Newtonsoft.Json.JsonProperty("password")]
        public string Pssd { get; set; }
    }
    

    请求

    {
      "username": "test",
      "password": "test"
    }
    
    Content-Type →application/json; charset=utf-8
    

    【讨论】:

    • 我有。但还是不行。身体只识别“Pssd”
    • 我试过了,它对我有用,我用示例源代码更新了答案
    • 它对我不起作用 :( 值是放在“密码”、test 还是 null 中?
    • 它的“测试”,这个工作正常。检查你的 api 有一些覆盖
    猜你喜欢
    • 2021-10-05
    • 2018-12-27
    • 1970-01-01
    • 2022-11-20
    • 2022-11-11
    • 2018-02-28
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多