Getting started with one of the ASP. NET Web APIs

Source: Internet
Author: User

A restful standards-based web API

Original explanation: https://www.cnblogs.com/lori/p/3555737.html

Microsoft's Web API is published on the MVC4 project bindings on vs2012, and its proposed Web API is completely based on the restful standard, completely different from the previous (as is the SOAP protocol) WCF and WebService, it is simple, code readable, quick to get started, If I want to compare it with the Web service, I would say that its interface is more standard, clearer, no confusing method name, some only a few standard requests, such as Get,post,put,delete, they correspond to several operations, the following:

Get: Raw to Data list (default), or get an Entity data

POST: Add a Service side to add a record that records the entity as a Form object

PUT: Add or modify a record on the service side, record the entity's Form object, and record the primary key to be transferred in a Get mode

Delete: Deletes a record on the service side

Self-brought example

 Public classValuescontroller:apicontroller {//GET api/values         Publicienumerable<string>Get () {return New string[] {"value1","value2" }; }        //GET API/VALUES/5         Public stringGet (intID) {return "value"; }        //POST api/values         Public voidPost ([Frombody]stringvalue) {        }        //PUT API/VALUES/5         Public voidPut (intID, [frombody]stringvalue) {        }        //DELETE API/VALUES/5         Public voidDelete (intID) {}}
Second, custom Web Api

Custom here is not much clever, plainly is accustomed to the way MVC, do not want to use the Restfull API

Modify Webapiconfig to achieve

 Public Static classWebapiconfig { Public Static voidRegister (httpconfiguration config) {//Web API Configuration and Services//Web API RoutingCONFIG.            Maphttpattributeroutes (); Config. Routes.maphttproute (Name:"Defaultapi", Routetemplate:"Api/{controller}/{action}/{id}", defaults:New{id =routeparameter.optional}); Config. Filters.add (NewValidatamodelattribute ()); Config. Filters.add (NewWebapiexceptionfilterattribute ()); //CONFIG. Filters.add (New Authfilterattribute ());//Because a Java httpclient request does not recognize the session, it is not usedCONFIG. Formatters.remove (config.         Formatters.xmlformatter); }    }

Webapi no session, you can open the session in Global.asax

  Public classWebApiApplication:System.Web.HttpApplication {//omit ....                protected voidapplication_postauthorizerequest () {if(Iswebapirequest ()) {HttpContext.Current.SetSessionStateBehavior (system.web.sessionstate.s            essionstatebehavior.required); }        }        Private BOOLiswebapirequest () {returnHttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith ("~/api"); }    }
Third, using model validation

Directly will step up, hehe

1. Defining Feature Filtering: Validatamodelattribute

Response Result: Return status 200, and error result hint, instead of 400 other states, return format inconsistent, status is not correct

 Public classValidatamodelattribute:actionfilterattribute { Public Override voidonactionexecuting (Httpactioncontext actioncontext) {if(!actionContext.ModelState.IsValid) {stringError =string.                Empty; foreach(varKeyinchActionContext.ModelState.Keys) {varState =Actioncontext.modelstate[key]; if(state. Errors.any ()) {error=State . Errors.first ().                        errormessage;  Break; }                }                varresult =NewErrorresult (Error); Actioncontext.response=ActionContext.Request.CreateResponse (Httpstatuscode.ok, result); //actionContext.Request.CreateErrorResponse (Httpstatuscode.badrequest, actioncontext.modelstate);            }        }     }

2. Defining Model Classes

can see: https://www.cnblogs.com/kexxxfeng/p/5602656.html

 Public class Pagemodel:basemodel    {        " the current page cannot be empty ")]        [Range (19999the current page must be greater than 0")]          Public int Get Set ; }    }

3. Using features

This will automatically verify the

[Validatamodel]        [HttpGet]          Public ihttpactionresult getpage ([Fromuri]pagemodel model)        {             var dataGrid = xxx;             return Jsondataresult (DataGrid);        }

Here by the way the problem of using dynamic, encountered dynamic type error: "Object" does not contain the definition of "XXX"

According to the online statement can not solve: https://www.cnblogs.com/similar/p/6716320.html

Iv.. Abnormal interception

Directly on the code

Log component go get it on your own. Webapiconfig inside configuration Note pairing

Application_Start Added filter: GlobalConfiguration.Configuration.Filters.Add (New Webapiexceptionfilterattribute ()); This is not sure if you really need it.

  Public classWebapiexceptionfilterattribute:exceptionfilterattribute {//overriding the exception handling method for a base class         Public Override voidonexception (Httpactionexecutedcontext actionexecutedcontext) {//1. Abnormal log records (usually in the official project with Log4net log exception logs)           varmsg = DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss") +"--"+ActionExecutedContext.Exception.GetType (). ToString ()+":"+ ActionExecutedContext.Exception.Message +"--Stack information:"+ActionExecutedContext.Exception.StackTrace;                         Loghelper.fatal (msg); //2. Return caller-specific exception information            if(actionexecutedcontext.exception isnotimplementedexception) {Actionexecutedcontext.response=Newhttpresponsemessage (httpstatuscode.notimplemented); }            Else if(actionexecutedcontext.exception istimeoutexception) {Actionexecutedcontext.response=Newhttpresponsemessage (httpstatuscode.requesttimeout); }            //..... Here you can return to the client-specific status code based on your project needs. If the corresponding exception is not found, the Unified return server error            Else{actionexecutedcontext.response=Newhttpresponsemessage (Httpstatuscode.internalservererror); }            Base.        Onexception (ActionExecutedContext); }    }
V. Token mechanism

This part has not been successful, it's just a record.

  

  Public classAuthfilterattribute:authorizeattribute { Public Override voidonauthorization (System.Web.Http.Controllers.HttpActionContext actioncontext) {//Remove the controller of the area controller,action            stringController =ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName; stringAction =ActionContext.ActionDescriptor.ActionName; if(Controller. ToLower () = =" Account"&& action. ToLower () = ="Login")            {                 Base.            Onauthorization (Actioncontext); }            Else            {                 varContent = actioncontext.request.properties["Ms_httpcontext"] asHttpContextBase; vartoken = content. request.querystring["Token"]; if(!string. IsNullOrEmpty (token)) {//URL Path                    stringFilePath =HttpContext.Current.Request.FilePath; //Verify that the user name password matches                    if(Validateticket (token) &&validdatepermission (token, controller, action, FilePath)) {                        Base.                    IsAuthorized (Actioncontext); }                    Else{handleunauthorizedrequest (actioncontext); }                }                //If authentication information is not available and anonymous access is not allowed, an unauthenticated 401 is returned                Else                {                    varattributes = Actioncontext.actiondescriptor.getcustomattributes<allowanonymousattribute> (). Oftype<allowanonymousattribute>(); BOOLisanonymous = attributes. Any (a = a isAllowanonymousattribute); if(isanonymous) {Base.                    Onauthorization (Actioncontext); }                    Else{handleunauthorizedrequest (actioncontext); }                }            }         }                 Private BOOLValidateticket (stringEncrypttoken) {            if(Userprovider.currentuser! =NULL&& UserProvider.CurrentUser.LoginToken = =Encrypttoken) {                return true; }            return false; }         Public BOOLValiddatepermission (stringTokenstringControllerstringActionstringFilePath) {            //bool Ispass = false; //TODO Permission Validation            return true; }    }

In addition, several related articles are recommended

WEBAPI series ~stringcontent parameters need to add Metatype object

WEBAPI Series ~httpclient Performance Pitfalls

WEBAPI Series ~ Invoking the Web API interface via HttpClient

WEBAPI Series ~ Call the Web API interface through the HttpClient ~ Cont ~ the delivery of entity parameters

WEBAPI Series ~ cors access in Webapi

Getting started with one of the ASP. NET Web APIs

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.