c# - how to return json error msg in asp.net web api? -
i return json errormessage @ moment in fiddler cannot see in json panel:
string error = "an error happened"; jsonresult jsonresult = new jsonresult { data = error, jsonrequestbehavior = jsonrequestbehavior.allowget }; response = request.createresponse(httpstatuscode.badrequest, jsonresult.data);
how this?
a few points:
if you're looking return error response containing simple error message, web api provides createerrorresponse
method that. can do:
return request.createerrorresponse(httpstatuscode.badrequest, "an error happened");
this result in following http response (other headers omitted brevity):
http/1.1 400 bad request content-type: application/json; charset=utf-8 content-length: 36 {"message":"an error happened"}
if want return custom object instead, use request.createresponse
doing, don't use mvc jsonresult
. instead, pass object directly createresponse
:
var myerror = new { data = "an error happened", otherdetails = "foo bar baz" }; return request.createresponse(httpstatuscode.badrequest, myerror);
now, doing you're not getting json server. important realize web api uses content type negotiation determine format use when sending response back. means, looks @ accept
header sent client request. if accept
header contains application/xml
, example, web api return xml. if header contains application/json
return json. so, should check client sending correct accept
header.
that said, there ways force web api return data in specific format if want. can @ method level using different overload of createresponse
specifies content type:
return request.createresponse(httpstatuscode.badrequest, myerror, new system.net.http.headers.mediatypeheadervalue("application/json"));
alternatively, can remove xml formatter configuration altogether in webapiconfig
file:
config.formatters.remove(config.formatters.xmlformatter);
this force web api use json regardless of client asks for.
Comments
Post a Comment