This article is about WEBAPI self-hosting, Webapi can be hosted on the console/winform/service, not necessarily rely on IIS.
1. Start a new console project and search through NuGet Microsoft.AspNet.WebApi.SelfHost
2, establish the entity class
1 Public classProduct2 {3 Public intId {Set;Get; }4 Public stringName {Set;Get; }5 Public stringDescription {Set;Get; }6}
3, create Webapi controller, inherit Apicontroller
1 Public classHomecontroller:apicontroller2 {3 StaticList<product> modellist =NewList<product>()4 {5 NewProduct () {id=1, name="Computer", description="Electrical Appliances"},6 NewProduct () {id=2, name="Refrigerator", description="Electrical Appliances"},7 };8 9 //Get all dataTen [HttpGet] One PublicList<product>GetAll () A { - returnmodellist; - } the - //get a piece of data - [HttpGet] - PublicProduct GetOne (intID) + { - returnModellist.firstordefault (p = p.id = =ID); + } A at //New - [HttpPost] - Public BOOLpostnew (Product model) - { - Modellist.add (model); - return true; in } - to //Delete + [Httpdelete] - Public BOOLDelete (intID) the { * returnModellist.remove (Modellist.find (p = p.id = =id)); $ }Panax Notoginseng - //Update the [Httpput] + Public BOOLPutone (Product model) A { theProduct Editmodel = modellist.find (p = = P.id = =model. ID); +Editmodel.name =model. Name; -Editmodel.description =model. Description; $ return true; $ } -}
4. Add the following code to the main method of program
1 Static voidMain (string[] args)2 {3 varConfig =NewHttpselfhostconfiguration ("http://localhost:5000");//Configuring Hosts4 5Config. Routes.maphttproute (//Configure Routing6 "API Default","Api/{controller}/{id}",7 New{id =routeparameter.optional});8 9 using(Httpselfhostserver server =NewHttpselfhostserver (config))//Listening for HTTPTen { OneServer. OpenAsync (). Wait ();//to open a request from a client AConsole.WriteLine ("Press Enter to quit"); - console.readline (); - } the}
5, I machine is win10, if the direct operation will be an error
WORKAROUND: Open the project path to find the project name. exe file right-click Run as Administrator
6. Access Http://localhost:5000/api/home by URL
Through WinForm, services and other means of hosting, this article no longer talk about, the way is similar, I think Webapi hosted on IIS is better than other ways, with the console, the presentation is good.
The next chapter is about WEBAPI cross-domain.
Self-host of getting Started with Web API (ii)