ErazerBrecht ErazerBrecht - 1 year ago 151
JSON Question

ASP.Net Core Error JSON

I'm playing a bit with ASP.NET Core. I'm creating a basic webapi.
I'd like to show a JSON error when there is a problem.

The printscreen shows want I want on my screen.
The only problem is that it's send with a statuscode of 200.


catch (NullReferenceException e)
return Json(NotFound(e.Message));

I could solve it by doing this:

return NotFound(new JsonResult(e.Message) {StatusCode = 404);

But I don't like this because now you can specify statuscode 500 with a NotFound.

Can someone put me in the correct direction?


Answer Source

Can't you do something like return NotFound(e.Message);

Or you might have your own error document format and go for return NotFound(new ErrorDocument(e.message));

If you have to return with a JsonResult then go for something like the following:

return new JsonResult(YourObject) { StatusCode = (int)HttpStatusCode.NotFound };

Now you have full control over response format and your status code too. You can even attach serializer settings if need be. :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download