[英]c# .net core web api x-www-form-urlencoded parameter is always null
I have this method that looks a bit like this:我有一个看起来有点像这样的方法:
/// <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);
}
When I use postman to send some data, it is always null.当我使用 postman 发送一些数据时,它总是 null。
Does anyone have any idea why this might be?有谁知道为什么会这样?
Create a model/DTO for the data being posted, .net core should handle the binding ( Model Binding in ASP.NET Core ).为要发布的数据创建模型/DTO,.net 核心应处理绑定( ASP.NET 核心中的 Model 绑定)。
You seem to already have WorldPayResponseModel
, so why not bind to that?您似乎已经拥有
WorldPayResponseModel
,那么为什么不绑定呢? For example:例如:
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);
}
You can also add DataAnnotations to the properties, then in the controller you can use ModelState.IsValid
.您还可以将 DataAnnotations 添加到属性中,然后在 controller 中您可以使用
ModelState.IsValid
。 Model validation in ASP.NET Core is a useful resource (it targets MVC/Razor pages, but model validation still works in an API). ASP.NET Core 中的 Model 验证是一个有用的资源(它针对 MVC/Razor 页面,但 model 验证仍然在 API 中工作)。
You can probably safely remove [FromForm]
too.您也可以安全地删除
[FromForm]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.