1.1.3 Host Web API in self host mode

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.