Starting today, the ASP. NET Web API (hereafter, sometimes referred to as the Web API) is studied. I will write a practical series of topics, not necessarily into a theoretical system, just encounter problems or experience, write down. Gain a deeper understanding of the ASP. NET Web API for a longer period of time. Here I use the VS2013 integrated development environment, if the version is not enough, you can use NuGet to download the Web API-related DLL.
Discuss the self-hosted web Api today.
The Web API inherits the benefits of WCF, and in addition to regular web hosting (IIS), it can be hosted in programs such as the Net console, WinForms, and so on. Here's a talk about hosting the Web Api in the console.
First, write the API method
New C # class library project Mycontrollers, referencing System.Web.Http.dll.
Write the API class file MyValuesController.cs:
using System.Web.Http; namespace mycontrollers{ publicclass myvaluescontroller:apicontroller { Public string Get () { return"OK";}} }
Second, add the Homestay project
Add a console project MYCONSOLEAPISVR, referencing the Mycontrollers project, referencing the following 4 Web API-related DLLs:
- System.Net.Http.dll
- System.Web.Http.dll
- System.Net.Formatting.Http.dll
- System.Web.Http.SelfHost.dll
The main program is as follows:
1 usingSystem;2 usingSystem.IO;3 usingSystem.Web.Http;4 usingSystem.Web.Http.SelfHost;5 usingSystem.Reflection;6 7 namespaceMyconsoleapisvr8 {9 class ProgramTen { One Static voidMain (string[] args) A { -Console.title ="Api Service"; - the varApidll = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,"MyControllers.dll"); - Assembly.LoadFrom (apidll); - varConfig =NewHttpselfhostconfiguration ("http://localhost:4588"); - CONFIG. Routes.maphttproute ( +Name"Defaultapi", -Routetemplate:"Api/{controller}/{id}", +DefaultsNew{id =routeparameter.optional}); A using(varSVR =Newhttpselfhostserver (config)) at { - SVR. OpenAsync (). Wait (); -Console.WriteLine ("API service is turned on! "); - console.readline (); - } - in } - } to}
The above code can be divided into several steps:
- Loads the DLL that contains the API controller method. (Line 16th)
- Add a service configuration and specify a service boarding address. (Line 17th)
- Adds a global default routing configuration. (第18-21 line)
- Define and open the service. (22nd, 24 lines)
Third, run the service and test
To run the Web API service:
and test in the browser:
ASP. NET Web Api Practice Series (i) Self-hosted