Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I customize the error response in Web API with .NET Core?

I am using .NET Core 2.2 with Web API. I have created one class, i.e., as below:

public class NotificationRequestModel
{
    [Required]
    public string DeviceId { get; set; }
    [Required]
    public string FirebaseToken { get; set; }
    [Required]
    public string OS { get; set; }

    public int StoreId { get; set; }
}

Using the above class I have created one method. Now I want to return a custom object, but it's returning its own object. API method is:

public ActionResult<bool> UpdateFirebaseToken(NotificationRequestModel model)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(FormatOutput(ModelState.Values));
    }
    var result = _notificationService.InsertOrUpdateFirebaseToken(model);
    return Ok(result);
}

Here FormatOutput method is format the output.

protected Base FormatOutput(object input, int code = 0, string message = "", string[] details = null)
{
    Base baseResult = new Base();
    baseResult.Status = code;
    baseResult.Error = message;
    baseResult.TimeStamp = CommonHelper.CurrentTimeStamp;
    baseResult.Code = code;
    baseResult.Details = details;
    baseResult.Message = message; //Enum.Parse<APIResponseMessageEnum>(code.ToString(), true); // (enum of code get value from language)
    return baseResult;
}

But the issue is it returns:

{
  "errors": {
    "DeviceId": [
      "The DeviceId field is required."
    ]
  },
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "80000049-0001-fc00-b63f-84710c7967bb"
}

I want to customize this error with my model. I need error message and details from return output and passed it to my model. How can I do that? I had try to debug my code and found that breakpoint on API method is not calling. So I can't handle my custom method. Is there any solution? What am I doing wrong?

like image 932
Srusti Thakkar Avatar asked Mar 01 '19 10:03

Srusti Thakkar


People also ask

How do I send a custom response in Web API?

Implementing a custom response handler in Web API. Create a new Web API project in Visual Studio and save it with the name of your choice. Now, select the Web API project you have created in the Solution Explorer Window and create a Solution Folder. Create a file named CustomResponseHandler.

What are the different ways to handle errors in Web API?

You can customize how Web API handles exceptions by writing an exception filter. An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception.


1 Answers

As Chris analyzed, your issue is caused by Automatic HTTP 400 responses.

For the quick solution, you could suppress this feature by

services.AddMvc()
        .ConfigureApiBehaviorOptions(options => {
            options.SuppressModelStateInvalidFilter = true;
        }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

For an efficient way, you could follow the suggestion from Chris, like below:

services.AddMvc()
        .ConfigureApiBehaviorOptions(options => {
            //options.SuppressModelStateInvalidFilter = true;
            options.InvalidModelStateResponseFactory = actionContext =>
            {
                var modelState = actionContext.ModelState.Values;
                return new BadRequestObjectResult(FormatOutput(modelState));
            };
        }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

And, there isn't any need to define the code below any more in your action.

if (!ModelState.IsValid)
{
    return BadRequest(FormatOutput(ModelState.Values));
}
like image 159
Edward Avatar answered Sep 21 '22 14:09

Edward