Common class and entity definition, Web API definitions See my previous article, hosting Web APIs as a web host.
I. To host a new console console project (Selfhost) with the self host
This project also needs to refer to the previously defined WEBAPI project or put WebApi.dll in the execution Bin directory of this project.
In addition, the DLLs that need to be referenced are as follows:
- System.Web.Http.dll (C:\Program Files (x86) \microsoft Asp.net\asp.net MVC 4\assemblies\system.web.http.dll)
- System.Web.Http.WebHost.dll(C:\Program Files (x86) \microsoft Asp.net\asp.net MVC 4\assemblies\ System.Web.Http.WebHost.dll)
- System.Net.Http.dll(C:\Program Files (x86) \reference Assemblies\microsoft\framework\. Netframework\v4.6\system.net.http.dll)
The specific code is as follows:
1 usingSystem;2 usingSystem.Reflection;3 usingSystem.Threading.Tasks;4 usingSystem.Web.Http;5 usingSystem.Web.Http.SelfHost;6 7 namespaceSelfhost8 {9 Internal Static class ProgramTen { One Private Static voidMain (string[] args) A { - //to load an assembly that contains a Web API -Assembly.Load ("WebApi, version=1.0.0.0, culture=neutral, Publickeytoken=null"); the - //configuration classes that use BaseAddress to initialize the HTTP service - varConfiguration =NewHttpselfhostconfiguration ("Http://localhost/selfhost"); - + //to generate a server instance that listens directly to HTTP - using(varHttpserver =Newhttpselfhostserver (configuration)) + { A //Registering Routes atHttpServer.Configuration.Routes.MapHttpRoute ("Defaultapi","Api/{controller}/{id}",New{id =routeparameter.optional}); - varTask =Httpserver.openasync (); - if(Task. Status = =taskstatus.waitingforactivation) - { -Console.WriteLine ("Http Server started!"); - } in Console.read (); - } to } + } -}
We must specify the type of homestay service when hosting a WCF service, but for an ASP. Web host or self host, we do not need to specify the type of Ihttpcontroller. That is, WCF service homestay is for a specific service type, while the ASP. NET Web API is hosted in batches. The bulk hosting of the ASP. NET Web API is derived from its intelligent parsing of the Httpcontroller type, which resolves all the Httpcontroller types from the assembly list. For webhost, it uses BuildManager to get the assemblies that are directly or indirectly referenced by the current project, but for self host, the type's resolution is by default only for the list of assemblies that are loaded into the current application domain.
Second, the test
Set Selfhost project as Startup Project, Ctrl+f5 execution program;
Host the Web API in the self host way