Reputation: 61
Morning All, I am using TryValidateModel on my Model to make sure certain required fields are met. According to the documentation this should return true if it is valid, and false if not.
When I use this on my .net core API instead of returning false with an invalid model it seems to be causing an exception and returning its own JSON as well as stopping any further code execution.
Is there a way to get it to just return false instead of throwing its own error so that I can return my own JSON.
When my Validation fails I am unable to use breakpoints, and the following JSON is returned.
{
"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."}
}
Edit: As requested code below
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
}
}
Upvotes: 1
Views: 2045
Reputation: 8312
You can use the Validate() method of the ApiController class to manually validate the model and set the 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" };
}
}
}
Upvotes: 2