0

I'm currently creating an ASP Web API and I found out that if requests are done to the API that contain empty values, that I receive "ugly" error exceptions in the ModelState that I don't want to show to my users. Let's say my request body looks like this:

{"Id": "", "Name": "", "Description": "", "Created": "", "UserId": "", "AmountOfUsers": "", "MinimumAmountOfUsers": "", "Location": "", "Activated": "", "CategoryId": "", "Date": ""}

Then I will receive the following ModelState exception for Id:

Error converting value {null} to type 'System.Int32'. Path 'Id', line 1, position 9

The same goes for all other value types.

I do have a [Required] data annotation (with custom error messages) for those fields in my model, but that does not seem to do the trick.

I am now wondering what the best solution is to resolve this. All the models that users post/put are view models, so I was thinking about making all value types nullable and then cast them afterwards when I map them to database models. I am unsure whether there are better solutions though and therefore I would love to hear you opinions.

David Tansey
  • 5,813
  • 4
  • 35
  • 51
user1796440
  • 366
  • 3
  • 11
  • Check for a [valid model state](http://stackoverflow.com/questions/11686690/handle-modelstate-validation-in-asp-net-web-api) and return an appropriate response. When are you getting that exception? What does you model class look like? – Jasen Dec 01 '15 at 23:50

1 Answers1

0

It is possible to control the error detail globally by modifying the IncludeErrorDetailPolicy of the web api config

https://msdn.microsoft.com/en-us/library/system.web.http.includeerrordetailpolicy(v=vs.118).aspx

config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Never;

Alternately you can check for exceptions in your action method and control the response that is sent back to the client

It is also possible to create a global exception filter to control detail

  public class MyExceptionHandler : IExceptionHandler {
    context.Result = new StatusCodeResult(HttpStatusCode.InternalServerError, context.Request);
   return Task.FromResult<object>(null);
  }

Then register that filter in the configuration

config.Services.Replace(typeof(IexceptionHandler), new MyExceptionHandler());
Bill
  • 1,241
  • 17
  • 25