ASP. NET Web Api practice series (1) Self-hosting, asp. netapi
Starting from today, we will study ASP. NET Web APIs (Web APIs ). I will write a series of practical topics, which may not necessarily be a theoretical system. I just want to write down my questions or experiences. We strive to gain a deeper understanding of ASP. NET Web APIs over a long period of time. Here I use VS2013 integrated development environment. if the version is not enough, you can use NuGet to download the Web Api-related dll.
Today we will discuss self-hosted Web APIs.
Web Api inherits the advantages of WCF. In addition to conventional Web hosting (IIS), it can also host in the NET console, WinForms, and other programs. Here we will talk about boarding Web APIs in the console.
I. Writing Api methods
Create the C # class library project MyControllers and reference System. Web. Http. dll.
Compile the Api file MyValuesController. cs:
using System.Web.Http;namespace MyControllers{ public class MyValuesController : ApiController { public string Get() { return "OK"; } }}
2. Add a boarding Project
Add a console project MyConsoleApiSvr, reference the MyControllers project, and reference the following four Web Api related DLL:
- 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 using System; 2 using System. IO; 3 using System. web. http; 4 using System. web. http. selfHost; 5 using System. reflection; 6 7 namespace MyConsoleApiSvr 8 {9 class Program10 {11 static void Main (string [] args) 12 {13 Console. title = "Api Service"; 14 15 var apiDll = Path. combine (AppDomain. currentDomain. baseDirectory, "MyControllers. dll "); 16 Assembly. loadFrom (apiDll); 17 var config = new HttpSelfHostCon Figuration ("http: // localhost: 4588"); 18 config. routes. mapHttpRoute (19 name: "DefaultApi", 20 routeTemplate: "api/{controller}/{id}", 21 defaults: new {id = RouteParameter. optional}); 22 using (var svr = new HttpSelfHostServer (config) 23 {24 svr. openAsync (). wait (); 25 Console. writeLine ("API service enabled! "); 26 Console. ReadLine (); 27} 28 29} 30} 31}
The above code can be divided into several steps:
3. Run and test the service
Run the Web Api service:
And test in the browser: