c# - Return JSON when Handling error in Web API -
i have created web api accepts 4 input parameters used in querying oracle database , returns result in json format. trying handle exception in uri if there input parameter missing or in wrong format . returning in json "error":"room cannot empty or null"
if room in uri empty room=&dob_gt=01-sep-05&dob_lt=30-dec-06&status_type=cmplt
public class tgsdatacontroller : apicontroller { [httpget] public httpresponsemessage getdetails(string room, datetime dob_gt, datetime dob_lt, string status_type) { if (string.isnullorempty(room)) { var resp = new httpresponsemessage() { content = new stringcontent("room cannot empty or null") }; resp.content.headers.contenttype = new mediatypeheadervalue("application/json"); return resp; } list<oracleparameter> prms = new list<oracleparameter>(); list<string> selectionstrings = new list<string>(); prms.add(new oracleparameter("room", oracledbtype.varchar2, room, parameterdirection.input)); prms.add(new oracleparameter("dob_gt", oracledbtype.date, dob_gt, parameterdirection.input)); prms.add(new oracleparameter("dob_lt", oracledbtype.date, dob_lt, parameterdirection.input)); prms.add(new oracleparameter("status_type", oracledbtype.varchar2, status_type, parameterdirection.input)); string connstr = configurationmanager.connectionstrings["tgsdatabaseconnection"].connectionstring; using (oracleconnection dbconn = new oracleconnection(connstr)) { dataset userdataset = new dataset(); var strquery = "select * lims_sample_results_vw room = :room , dob > :dob_gt , dob < :dob_lt , status_type= :status_type "; var returnobject = new { data = new oracledatatablejsonresponse(connstr, strquery, prms.toarray()) }; var response = request.createresponse(httpstatuscode.ok, returnobject, mediatypeheadervalue.parse("application/json")); contentdispositionheadervalue contentdisposition = null; if (contentdispositionheadervalue.tryparse("inline; filename=tgsdata.json", out contentdisposition)) { response.content.headers.contentdisposition = contentdisposition; } return response; }
with code above return room cannot empty or null how "error":"room cannot empty or null"
. there way handle error in urli , return json response "error":"poorly formed uri"
you can build anonymous type error(s) want return.
if (string.isnullorempty(room)) { return this.request.createresponse( httpstatuscode.badrequest, new { error= "room cannot empty or null" }); resp.content.headers.contenttype = new mediatypeheadervalue("application/json"); return resp; }
Comments
Post a Comment