Konsultan IT Bandung
Konsultan IT Bandung

Reputation: 151

Custom API Response Data Annotation

I'm currently building a Web API, I'm having problems displaying a response when there is an error in DataAnnotation Validation

Here is the code:

public class NewPatient
{
  [StringLength(13)]
  [Required(ErrorMessage = "Format Nomor Kartu Tidak Sesuai")]
  public string nomorkartu { get; set; }
  
  [StringLength(16)]
  [Required(ErrorMessage = "Format NIK Tidak Sesuai")]
  public string nik { get; set; }
}

When the validation runs, the Validation above returns a response like this:

{
  "errors": {
    "nomorkartu": [
      "Format Nomor Kartu Tidak Sesuai."
    ]
  },
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-5dc8a15c7bf9dfe1e99d3312fbfe16f7-368da3671328539c-00"
}

How can I display a format like the following response:

{
  "metadata":{
    "code":"400",
    "message": "Format Nomor Kartu Tidak Sesuai."
  }
}

thank you

Upvotes: 2

Views: 1103

Answers (1)

Rahul Sen
Rahul Sen

Reputation: 101

You can do that by adding the following code in the startup.

public class NewPatient
{
  [StringLength(13)]
  [Required(ErrorMessage = "Format Nomor Kartu Tidak Sesuai")]
  public string nomorkartu { get; set; }
  
  [StringLength(16)]
  [Required(ErrorMessage = "Format NIK Tidak Sesuai")]
  public string nik { get; set; }
}

Add the code in the startup

// Added custom response for modle validation error

services.AddMvcCore().ConfigureApiBehaviorOptions(options => {
            options.InvalidModelStateResponseFactory = (errorContext) =>
            {
                var errors = errorContext.ModelState.Values.SelectMany(e => e.Errors.Select(m => new
                {
                    ErrorMessage = m.ErrorMessage
                })).ToList();
                var result = new
                {
                    Metadata = new
                    {
                        Code = (int)HttpStatusCode.BadRequest,
                        Message = errors.Select(e => e.ErrorMessage).ToList()
                    }
                };
                return new BadRequestObjectResult(result);
            };
        });

Upvotes: 4

Related Questions