The hosted Web API does not necessarily require IIS support, and we can use the self host to host any type of application (console, Windows Forms application, WPF).
For an empty console app such as Selfhost, you need to reference the following assemblies in addition to the projects that reference Webapi
System.Web.Http
System.Web.Http.SelfHost
System.Net.Http
The only thing that a hosted Web API needs to do for web host is route registration. But for self host, in addition to the necessary route registration, we need to do something extra,
That is, manually loading an assembly that defines the Httpcontroller type.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Reflection;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Web.Http;usingSystem.Web.Http.SelfHost;namespaceseifhost{classProgram {Static voidMain (string[] args) {Assembly.Load ("WebApi, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = null"); Httpselfhostconfiguration Configuration=NewHttpselfhostconfiguration ("Http://localhost/selfhost"); using(Httpselfhostserver httpserver =Newhttpselfhostserver (configuration)) {HttpServer.Configuration.Routes.MapHttpRoute (name:"Defaultapi", Routetemplate:"Api/{controller}/{id}", defaults:New{id =routeparameter.optional}); Httpserver.openasync (); Console.WriteLine ("I have started and the pro can be previewed in the browser. "); Console.read (); } } }}
We start the program F5
Then enter http://localhost/selfhost/api/Contacts/001 in the browser
The self host host for the ASP. NET Web API is completed by Httpselfhostserver
1.1.3 Host Web API in self host mode