2

We often have the case that clients call our ASP.NET API with an invalid JSON. The mistakes can be anywhere from wrong fields to wrong formatting. Yes, you could argue that this is the clients problem, but this will not make my life easier.

Is there a way to get to whatever the client sent us, if the controller throws an Exception?

Remy
  • 12,555
  • 14
  • 64
  • 104
  • 1
    Yes, you can read the raw string request in HTTP format as well as its body as a string. Malformated jsons are there, can be for example logged for later investigation. – Al Kepp May 09 '19 at 23:33
  • You can try to use asp.net Action Filters - they are calls before your request gets Action. Or you can use Application_BeginRequest to handle all requests. – Alex Kvitchastyi May 10 '19 at 01:57
  • You can try by using JTokenParser from JSON.Net, the post about it https://stackoverflow.com/questions/14977848/how-to-make-sure-that-string-is-valid-json-using-json-net – Ivan May 10 '19 at 06:48
  • the way to help the clients is to provide something which details how to use the api, like Swagger. That should make the support a lot easier. – Andrei Dragotoniu May 10 '19 at 07:11

1 Answers1

1

This code snippet will allow you to see the raw content of the request body:

using (var reader = new System.IO.StreamReader(System.Web.HttpContext.Current.Request.InputStream))
{
    var content = reader.ReadToEnd();  // raw content of request body
}
awj
  • 7,482
  • 10
  • 66
  • 120