c# - Custom json response body for HTTP errors -


i'm wondering if there way in api controllers return custom object response body methods like: badrequest() or notfound().

for example, 404 error, i'd return like:

{   "statuscode": 404,   "error": "not found",   "message": "custom message..." } 

instead i'm getting this:

{   "message": "custom message..." } 

at moment return complex response body i'm using ok() way:

return ok(new {     success = false,     message = "custom message...",     // other fields... }); 

but i'm returning 200 status not meaningful.

is there better way achieve this?

long way

if need quick solution jump short way, read understand how works under hood. derive own jsonerrorresult class derived jsonresult:

public sealed jsonerrorresult : jsonresult {     public jsonerrorresult(statuscodes statuscode, object value)         : base(value)     {         _statuscode = statuscode;     }      private readonly jsonerrorresult statuscodes _statuscode; } 

now override executeresultasync() method change status code of default jsonresult implementation:

public override task executeresultasync(actioncontext context) {     context.httpcontext.response.statuscode = _statuscode;     return base.executeresultasync(context); } 

you return calling badrequest() this:

return new jsonerrorresult(statuscodes.status400badrequest, new  {     statuscode = "404",     error = "bla bla bla",     message = "bla bla bla" }); 

of course if use may want create own helper method:

protected static jsonerrorresult jsonerror(statuscodes statuscode,                                            string error, string message) {     return new jsonerrorresult(statuscode, new      {         statuscode = convert.tostring((int)statuscode),         error = error,         message = message     }); } 

used this:

return jsonerror(statuscodes.status400badrequest, "bla bla bla", "bla bla bla"); 

short way

jsonresult has statuscode property helper method may become this:

protected static jsonresult jsonerror(statuscodes statuscode,                                            string error, string message) {     var result = new jsonresult(new      {         statuscode = convert.tostring((int)statuscode),         error = error,         message = message     });      result.statuscode = (int)statuscode;      return result; } 

Comments