1. Add a Webapi Controller, VS will automatically add related references, mainly system.web.http,system.web.http.webhost,system.net.http
2. Create the WebApiConfig.cs and register the route under App_start
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Web.Http;namespacelibaray.web.app_start{ 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}/{id}", defaults:New{id =routeparameter.optional}); } }}
View Code
3. Add WebAPI configuration under Global.asax, Application_Start
usingLibaray.Web.App_Start;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSystem.Web.Http;usingSYSTEM.WEB.MVC;usingSystem.Web.Optimization;usingSystem.Web.Routing;namespacelibaray.web{ Public classMvcApplication:System.Web.HttpApplication {protected voidApplication_Start () {arearegistration.registerallareas (); Globalconfiguration.configure (Webapiconfig.register); Filterconfig.registerglobalfilters (globalfilters.filters); Routeconfig.registerroutes (routetable.routes); Bundleconfig.registerbundles (Bundletable.bundles); } }}
View Code
4. Fill in the corresponding code in the WEBAPI added in the first step,
usingLibaray.Web.Models;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net;usingSystem.Net.Http;usingSystem.Web.Http;namespacelibaray.web.controllers{[Routeprefix ("api/systemusers")] Public classSystemuserscontroller:apicontroller {[HttpGet, Route ("getuserlist")] PublicList<usermodel>Getusermodels () {Usermodelservice userbs=NewUsermodelservice (); returnUserbs.findlist (U = u.isactive = =true); } [HttpGet, Route ("GetUser")] PublicUsermodel Getusermodel (intID =0) { if(id! =0) {Usermodelservice userbs=NewUsermodelservice (); returnUserbs.find (U = u.id = =ID); } Else { return NULL; }} [HttpPost, Route ("Login")] Public BOOLLogin (stringLoginId,stringpassword) {Usermodelservice Userbs=NewUsermodelservice (); returnuserbs.validatelogininfo (loginId, password); } }}
View Code
5. Run the application and call the API. Example:http://localhost:49919/api/systemusers/getuserlist
6. Some questions
After the above configuration, run the Web page, still can not get the desired results, after detection because I was in the areas built an API folder
As soon as you delete the View folder and the APIAreaRegistration.cs file, the problem disappears, the specific reason is not scrutiny, it should still be a routing problem.
Reference:
Https://www.cnblogs.com/tuyile006/p/6151555.html
Webapi-1 add Webapi to an existing MVC project