早上好,我在模型上使用TryValidateModel来确保满足某些必填字段。根据文档,如果有效,则应返回true,否则应返回false。
当我在.net核心API上使用它而不是使用无效模型返回false时,它似乎会导致异常并返回其自己的JSON并停止任何进一步的代码执行。
有没有办法让它返回false而不是抛出自己的错误,以便我可以返回自己的JSON。
当我的验证失败时,我将无法使用断点,并返回以下JSON。
{
"errors": {"RepairOrder.ReferenceNumber": ["The ReferenceNumber field is required."]},
"type": null,
"title": "One or more validation errors occurred.",
"status": 400,
"detail": null,
"instance": null,
"extensions": {"traceId": "|514b9bb2-4999b11a49fa3351."}
}
编辑:按以下要求的代码
using System.ComponentModel.DataAnnotations;
namespace Bright.Models
{
public class CreateRepairOrderRequest
{
public RepairOrder RepairOrder { get; set; }
}
public class RepairOrder
{
[Required]
public string ReferenceNumber { get; set; }
}
}
using Bright.Models;
using Microsoft.AspNetCore.Mvc;
namespace Bright.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class CreateRepairOrderController : ControllerBase
{
[HttpPost]
public CreateRepairOrderResponse Post(CreateRepairOrderRequest createRequest)
{
if(!TryValidateModel(createRequest))
return new CreateRepairOrderResponse() { AckMessage = "Creation Failed: Missing required field", RetCode = "1" }; //This line is never executed when TryValidateModel fails
}
}
答案 0 :(得分:1)
您可以使用Validate(类的ApiController)方法来手动验证模型并设置ModelState。
using Bright.Models;
using Microsoft.AspNetCore.Mvc;
namespace Bright.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class CreateRepairOrderController : ControllerBase
{
[HttpPost]
public CreateRepairOrderResponse Post(CreateRepairOrderRequest createRequest)
{
this.Validate(createRequest);
if (!ModelState.IsValid)
{
//return BadRequest(ModelState);
return new CreateRepairOrderResponse() { AckMessage = "Creation Failed: Missing required field", RetCode = "1" };
}
}
}