WEBAPI Global Exception handling methods

Source: Internet
Author: User

Custom error messages

 public class Errormessage:delegatinghandler {protected override task

Global exception handling includes 404

public class Notfoundactionselector:apicontrolleractionselector {public override Httpactiondescriptor Selectac            tion (httpcontrollercontext controllercontext) {httpactiondescriptor decriptor = null; try {decriptor = base.            SelectAction (ControllerContext); } catch (Httpresponseexception ex) {var code = Ex.                Response.statuscode;                if (Code! = Httpstatuscode.notfound && Code! = httpstatuscode.methodnotallowed) throw;                var routedata = Controllercontext.routedata;                Routedata.values["action"] = "Handle404";                Ihttpcontroller Httpcontroller = new Errorcontroller ();                Controllercontext.controller = Httpcontroller; Controllercontext.controllerdescriptor = new Httpcontrollerdescriptor (controllercontext.configuration, "Error",                Httpcontroller.gettype ()); Decriptor =Base.            SelectAction (ControllerContext);        } return decriptor; }    }

  

public class Notfoundcontrollerselector:defaulthttpcontrollerselector    {public        Notfoundcontrollerselector (httpconfiguration configuration)            : Base (Configuration)        {        } public        override Httpcontrollerdescriptor Selectcontroller (httprequestmessage request)        {            Httpcontrollerdescriptor Decriptor = null;            Try            {                Decriptor = base. Selectcontroller (request);            }            catch (Httpresponseexception ex)            {                var code = ex. Response.statuscode;                if (Code! = httpstatuscode.notfound)                    throw;                var routevalues = Request. Getroutedata (). Values;                routevalues["Controller" = "Error";                Routevalues["action"] = "Handle404";                Decriptor = base. Selectcontroller (request);            }            return decriptor;        }    }

Permission filtering

public class Supportfilter:authorizeattribute {//Override base class validation method, add our custom ticket verify Redishelper Redis = new Re        Dishelper (1); public override void Onauthorization (System.Web.Http.Controllers.HttpActionContext actioncontext) {//ur            L Get token var content = actioncontext.request.properties["Ms_httpcontext"] as httpcontextbase; var token = content.            request.querystring["Token"]; var userid = content. request.querystring["userid"]! = null? Int. Parse (content.            request.querystring["userid"]): 0; var mac = content. Request.querystring["Mac"]! = null? Content.            Request.querystring["Mac"]: null;            var routes = new RouteCollection ();            Routeconfig.registerroutes (routes); Routedata Routedata = routes.            Getroutedata (content);            The controller of the extraction area Action,id string controller = ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName; String action = Actioncontext.actionDescriptor.actionname;            URL path string filePath = HttpContext.Current.Request.FilePath; if (Controller. ToLower () = = "User" && action. ToLower () = = "Login") | | (Controller. ToLower () = = "User" && action. ToLower () = = "Register") | | (Controller. ToLower () = = "banner" && action. ToLower () = = "Getbanner") | | (Controller. ToLower () = = "Device" && action. ToLower () = = "Login") {} else {var attribute s = actioncontext.actiondescriptor.getcustomattributes<allowanonymousattribute> ().                Oftype<allowanonymousattribute> (); BOOL isanonymous = attributes.                Any (a = A is allowanonymousattribute); if (isanonymous) base.                Onauthorization (Actioncontext); if (userid! = 0 && Token! = null && token. Length > 0) {if (Redis. Stringget ("User_token_" + userid.)ToString ())! = token) {handleunauthorizedrequest (actioncontext); }} else if (Mac! = NULL && token! = null && token. Length > 0) {if (Redis. Stringget ("Device_token_" + Mac)! = token) {handleunauthorizedrequest (Actioncon                    Text);            }} else Handleunauthorizedrequest (Actioncontext); }} protected override void Handleunauthorizedrequest (Httpactioncontext actioncontext) {b Ase.            Handleunauthorizedrequest (Actioncontext); if (ActionContext.Response.StatusCode = = System.Net.HttpStatusCode.Unauthorized) {Actioncontext . Response.content = new Stringcontent (SERIALIZEUTILS&LT;BASERESMODEL&LT;BASEMODEL&GT;&GT;. Serialize (New Basemodel () {Errorno = -4, errormsg = ""}), SysteM.text.encoding.utf8, "Application/json"); }        }    }

  

  

Configuring in Webconfig

   Config. Messagehandlers.add (New ErrorMessage ());            Config. Filters.add (New Supportfilter ());            Config. Services.replace (typeof (Ihttpcontrollerselector), new Notfoundcontrollerselector (config));            Config. Services.replace (typeof (Ihttpactionselector), New Notfoundactionselector ());            Web API Routing            config. Maphttpattributeroutes ();            Config. Routes.maphttproute (                name: "Defaultapi",                routetemplate: "Api/{controller}/{id}",                defaults:new {id = Routeparameter.optional}            );            Config. Routes.maphttproute (              name: "Error404",              routetemplate: "{*url}",              defaults:new {controller = "Error", Action = "Handle404"}          );

  

Webapi Global Exception handling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.