c# - Exception from MVC API to MVC site gives error -
i have created mvc (4) web api works fine. has simple login-method throws exception when user cannot found.
besides api created simple website calls api httpclient:
public t executepost<t>(string apiurl, ienumerable<keyvaluepair<string, string>> postdata) { httpcontent content = null; if (postdata != null) content = new formurlencodedcontent(postdata); var = _client.postasync(apiurl, content).continuewith(httpresponsemessage => jsonconvert.deserializeobject<t>(httpresponsemessage.result.content.readasstringasync().result) ); return a.result; }
you can call method
executepost<user>("url_to_controller_action_api", list_with_keys_and_values_to_post)
when method calls api postdata-fiels username , password (both correct , known system) object called user returned... works charm. when call method wrong username and/or password, api throws exception (user not found), method executepost throws exception aswell , web page shows nice, yellow-isch, red-letter page errors normal user not understand. reason easy: data sent api not same data can put in object user.
so, deserialize exception, api, in object called error , return controller of mvc website, can put error "user not found" on page correct design of site.
what best way this? try-catch in actions? doesn't feel right me... suggestions more welcome.
most things found api-side stuff, want fetch , handle exception on site-side.
thanks in advance
on web api when detect invalid login, make sure httpresponseexception
gets thrown status code of 401 (httpstatuscode.unauthorized
).
//login failed: var resp = new httpresponsemessage(httpstatuscode.unauthorized) { content = new stringcontent("invalid username or password") }; throw new httpresponseexception(resp);
in calling code, can first check if httpresponsemessage.statuscode==httpstatuscode.ok
before attempt deserialise response user
.
var = _client.postasync(apiurl, content).continuewith(httpresponsemessage => { if (httpresponsemessage.status!=httpstatus.ok) { string errormessage = httpresponsemessage.result.content.readasstringasync(); //and whatever want error message here } else { try { var user = jsonconvert.deserializeobject<t>(httpresponsemessage.result.content.readasstringasync().result); } catch(exception ex) { //honest goodness unrecoverable failure on webapi. //all can here fail gracefully caller. } }//endif (status ok) }//end anonymous function );
if it's not 200 can execute second check see if it's 401 (and have specific handling invalid login) or more general 500 (something went wrong on server), etc, , actual error message of exception ("invalid username or password") send client:
var errormessage = httpresponsemessage.content.readasstringasync().result;
finally, if 200 should still try...catch
deserialisation operation can gracefully handle issues returned data, if whatever reason data can't turned user
object.
Comments
Post a Comment