1

I have asp.net web api application. When I try to send request with invalid Json to my api, the response is bad request. how can i change response client message? I try InvalidModelStateResponseFactory and ModelBindingMessageProvider in ASP.NET Core Model Binding Error Messages Localization

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    [HttpPost]
    public void Post([FromBody] ForTestJson request)
    {
        //some operation after validation
    }

}

public class ForTestJson
{
    public long Id { get; set; }
    public string Name { get; set; }
    public DateTimeOffset DateTimeOffset { get; set; }
}

the request is like below with invalid type of Id and DateTimeOffset

{
  "id": "aaa",
  "name": "string",
  "dateTimeOffset": "bbb"
}

the response is

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-a3ab5818c8cdc45073d5f5c8941887e9-3fcff0b267c68057-00",
  "errors": {
    "request": [
      "The request field is required."
    ],
    "$.id": [
      "The JSON value could not be converted to System.Int64. Path: $.id | LineNumber: 1 | BytePositionInLine: 13."
    ]
  }
}

I want to change "The JSON value could not be converted to ..." to another message

Peter Csala
  • 17,736
  • 16
  • 35
  • 75

1 Answers1

0

Your request body cannot be deserialized to an instance of ForTestJson because the data types of the id and dateTimeOffset properties in the request don't match those of the corresponding properties in the ForTestJson class.

If you want to return a different error message, you could change the signature of your Post method to accept a string rather than a ForTestJson instance, and then write your own code in the Post method to attempt to deserialize the string from JSON to a ForTestJson instance, catch any exceptions thrown during deserialization, interpret the exceptions and build your own error message from them.

sbridewell
  • 777
  • 4
  • 16