skip to Main Content

I have a simple class for the POST request body:

[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
    [HttpPost]
    public IActionResult Post(PostRequest request)
    {
        return Ok();
    }
}

public class PostRequest
{
    [Required]
    public String String { get; set; }
}

If I send an int instead of a string, the following error message is returned:

"$.string": [
"The JSON value could not be converted to System.String. Path: $.string | LineNumber: 1 | BytePositionInLine: 13."] }

I don’t feel like exposing what happens under the hood is right. Is there a way to return a generic "The field String is invalid" message?

2

Answers


  1. I’m not sure, but maybe this will help you. Paste this code at the very beginning of the method:

    if (!ModelState.IsValid)
     {
         return BadRequest();
     }
    
    
    Login or Signup to reply.
  2. This error comes from System.Text.Json.JsonSerializer inside SystemTextJsonInputFormatter durring desrializing request body into the model and you can disable it like below:

    builder.Services.AddControllers().AddJsonOptions(options =>
        options.AllowInputFormatterExceptionMessages = false);
    

    And you will relieve error message like this:

    {
      "$.string": [
        "The input was not valid."
      ]
    }
    

    You can also customize error message and get rid of $. like below:

    builder.Services.Configure<ApiBehaviorOptions>(o =>
    {
        //we need to call this original factory inside our custom factory
        var originalFactory = o.InvalidModelStateResponseFactory;
        o.InvalidModelStateResponseFactory = context =>
        {
            //get all the keys prefixed with $. (which should be related to json errors)
            var jsonPathKeys = context.ModelState.Keys.Where(e => e.StartsWith("$.")).ToList();
            foreach (var key in jsonPathKeys)
            {
                var normalizedKey = key.Substring(2);
                foreach (var error in context.ModelState[key].Errors)
                {
                    if (error.Exception != null)
                    {
                        context.ModelState.TryAddModelException(normalizedKey, error.Exception);
                    }
                    context.ModelState.TryAddModelError(normalizedKey, "The provided value is not valid.");
                }
                context.ModelState.Remove(key);
            }
            return originalFactory(context);
        };
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search