【问题标题】:c# .net core web api x-www-form-urlencoded parameter is always nullc# .net core web api x-www-form-urlencoded 参数始终为null
【发布时间】:2020-03-11 01:17:44
【问题描述】:

我有这个方法,看起来有点像这样:

/// <summary>
/// Updates the status to paid
/// </summary>
/// <param name="data">The data from world pay</param>
/// <returns></returns>
[HttpPost]
[Consumes("application/x-www-form-urlencoded")]
public IActionResult Residential([FromForm] string data)
{
    if (string.IsNullOrEmpty(data)) return BadRequest("No data was present");

    var model = JsonConvert.DeserializeObject<WorldPayResponseModel>(data);

    // ----- removed from brevity ----- //

    return Ok(true);
}

当我使用邮递员发送一些数据时,它总是为空。

有人知道为什么会这样吗?

【问题讨论】:

  • 你有没有想过这个问题?我也有同样的问题。
  • 使用IActionResult Method([FromForm] IFormCollection form) 而不是string

标签: c# asp.net-core-webapi x-www-form-urlencoded


【解决方案1】:

为要发布的数据创建模型/DTO,.net 核心应处理绑定 (Model Binding in ASP.NET Core)。

您似乎已经拥有WorldPayResponseModel,那么为什么不绑定它呢?例如:

public class WorldPayResponseModel
{
    public string CardType { get; set; } 
    public int CardId { get; set; } 
    // other properties
    ...
}

[HttpPost]
[Consumes("application/x-www-form-urlencoded")]
public IActionResult Residential([FromForm] WorldPayResponseModel model)
{
    if (model == null || !ModelState.IsValid) return BadRequest("No data was present");    

    // ----- removed from brevity ----- //

    return Ok(true);
}

您还可以将 DataAnnotations 添加到属性中,然后在控制器中您可以使用ModelState.IsValidModel validation in ASP.NET Core 是一个有用的资源(它针对 MVC/Razor 页面,但模型验证仍然在 API 中工作)。

您也可以安全地删除[FromForm]

【讨论】:

  • 我做了同样的事情,但我仍然在 CardType 中获得了 null
猜你喜欢
  • 2018-08-09
  • 2019-05-18
  • 2017-08-28
  • 2014-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-06
  • 2019-01-03
相关资源
最近更新 更多