Self server selfhost

  • Tutorial
We write "our own server" using the namespace classes System.Web.Http.SelfHost.

Faced with the use of the classes of this namespace when it became necessary to write a web muzzle accessible from:

imageWindows service.

Let's create two projects
1st - actually our
2nd server will contain api controllers

Our server will look like this:

public class HTTPServer
		public static string ServiceAddress = string.Format("http://{0}:{1}", 
                          Common.Config.HTTPServerIP /*собственно прописываем IP*/, 
                          Common.Config.HTTPServerPort /*а здесь прописываем порт*/);
		private HttpSelfHostServer _HTTPserver = null;
		private static HttpSelfHostConfiguration _config = null;
		private static HttpSelfHostServer CreateHost()
			_config = new HttpSelfHostConfiguration(ServiceAddress);
			AssembliesResolver assemblyResolver = new AssembliesResolver();
			_config.Services.Replace(typeof(IAssembliesResolver), assemblyResolver);
			  name: "default",
			  routeTemplate: "api/{controller}/{action}/{id}",
			  defaults: new { controller = "Home", id = RouteParameter.Optional });
			HttpSelfHostServer server = new HttpSelfHostServer(_config);
			return server;
		public void Start()
			_HTTPserver = CreateHost();
		public void Stop()
			if (_HTTPserver != null)

Now our service needs to specify where our api controllers will come from, for this we inherit the class in the server project:


class AssembliesResolver : DefaultAssembliesResolver
		public override ICollection GetAssemblies()
			ICollection baseAssemblies = base.GetAssemblies();
			List assemblies = new List(baseAssemblies);
			string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Infrastructure.Server.HTTP.Controllers.dll" /*библиотека, получившаяся при компиляции проекта с api контроллерами */);
			return assemblies;

We pass to the second project with controllers. Here we add a class whose name should contain the ending of the Controller, for example:

Users Controller
Regions Controller
Devices Controller

Overload the ApiController class of the System.Web.Http namespace and add several methods:

public class UsersController : ApiController
		public object hello()
			return "Hello page";
		public object SendData(int data)
			return new HttpResponseMessage(HttpStatusCode.OK);

Let's pay attention to the line again:


This line describes the route pattern.
We will send requests to the ip-address and port specified in ServiceAddress, then write / api , then / the name of our controller class without the Controller prefix , for example:

, and then / the name of the method and the list of parameters via &

To debug the application I am using the Postman Chrome extension - REST Client .

Here is an example of Get request: : 8080 / api / Users / Hello

Here is an example of Post request: : 8080 / api / Users / SendData? data = 1

Also popular now: