Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a data object with a BadRequestResult / BadRequestErrorMessageResult

I'd like to return a data object that contains the details of the error with a BadRequestErrorMessageResult or BadRequestErrorMessageResult object like so:

public IHttpActionResult Action(Model model)
{
  var validationResult = model.Validate();
  if (validationResult.Successful)
  {
    // this one's okay; it supports sending data with a 200
    return Ok(validationResult);
  }
  else
  {
    // However, how do I return a custom data object here
    // like so?
    // No such overload, I wish there was

    // return BadRequest(validationResult);
  }
}

The only three overloads of the ApiController.BadRequest() method are:

1. BadRequest();
2. BadRequest(string message);
3. BadRequest(ModelStateDictionary modelState);

Even with #3, a model state dictionary is ultimate a deep collection with one layer upon another, at the bottom of which, though, is a bunch of KeyValuePair<string, ModelError> where each ModelError also only has either a string or an Exception object.

Therefore, even with #3, we are only able to pack a string to send and not a custom object like I want to.

I am really not asking how I may go about working a hack or a kludge around the situation. My question is: is there an overload or another way baked into the .NET API to send an object to the client with a Bad Request HTTP status code?

I am using ASP.NET Web API version 5.2.4 targeting .NET Framework version 4.6.1.

like image 519
Water Cooler v2 Avatar asked Jun 20 '26 06:06

Water Cooler v2


1 Answers

You can use the Content<T>(...) method to do this. It returns a NegotiatedContentResult, which is serialized depending on the request headers (e.g. json, xml), and allows you to specify a HttpStatusCode.

You can use it like this:

return Content(HttpStatusCode.BadRequest, myObject);

If you wanted to, you could create your own BadRequest<T>(T obj) method in the controller as a wrapper, so then you could call it as you wanted:

public IHttpActionResult BadRequest<T>(T obj)
{
    return Content(HttpStatusCode.BadRequest, obj);
}

public IHttpActionResult Action()
{
    // do whatever validation here.
    var validationResult = Validate();

    // then return a bad request
    return BadRequest(validationResult);
}
like image 168
Zac Faragher Avatar answered Jun 22 '26 14:06

Zac Faragher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!