【发布时间】:2021-05-09 02:02:53
【问题描述】:
我有一个 ASP.NET Core 2.1 Web API 应用程序。如果我将空引号作为请求正文中的 json 对象属性值发送到 API 端点,我将使用 null 初始化该属性(它是 Guid 类型?)。我怎样才能改变这种行为?我需要的只是发送 BadRequest (400) 作为响应错误代码。
那是一个端点:
public async Task<ActionResult<ExampleResponse>> ExamplePatch([FromBody] ExampleModel exampleModel,
CancellationToken cancellationToken)
{
/* At this point exampleModel.ExampleGuid is initilized with null. So it should be handled before */
/* some processing */
return StatusCode(StatusCodes.Status201Created, ExampleResponse);
}
这是模型:
[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "9.10.53.0 (Newtonsoft.Json v9.0.0.0)")]
public class ExampleModel
{
/* a bunch of properties here */
[Newtonsoft.Json.JsonProperty("exampleGuid", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public System.Guid? ExampleGuid { get; set; }
}
请求正文中的 JSON:
{ ... other parameters here ..., "exampleGuid": "" }
我对此有一个限制 - 我不能向该模型属性添加属性或以某种方式更改模型。非常感谢您的帮助!
【问题讨论】:
标签: c# asp.net-mvc asp.net-core json.net asp.net-core-webapi