model view controller - WebApi: Reading errors -
i've got simple web api consumed mvc project, keep on getting 'response status code not indicate success' , wondering how response body error, can see error within rest viewer can't navigate through error. following code within mvc app
public actionresult index() { try { var uri = "http://localhost:57089/api/values"; using (var client = new httpclient()) { task<string> response = client.getstringasync(uri); object result = jsonconvert.deserializeobject(response.result); return (actionresult) result; } } catch (exception ex) { return content(ex.tostring()); } return view(); }
within api controller i'm sending bad request, here's code
public ihttpactionresult get() { return badrequest("this bad request " + system.datetime.now.touniversaltime()); }
i've tried use webexception, httprequestexception exceptions catch error no luck.
i can see response body within rest viewer
i want able navigate error message can pass client (which later changed guid).
[edited]
i've got solution without using getstringasync, wanted use if possible.
here's solution
var httpclient = new httpclient(); httpclient.baseaddress = new uri(url); httpresponsemessage responsemessage = httpclient.getasync("").result; if (responsemessage.issuccessstatuscode) return content(responsemessage.tostring()); var = responsemessage.content.readasstringasync().result; var result = jsonconvert.deserializeobject<httperror>(a); object value = ""; return content(result.trygetvalue("errormessage", out value) ? value.tostring() : responsemessage.tostring());
is there better way?
using webexception
should able responsestream
, custom error message this:
catch (webexception e) { var message = e.message; using (var reader = new streamreader(e.response.getresponsestream())) { var content = reader.readtoend(); } }
hope helps.
Comments
Post a Comment