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);
			_config.Routes.MapHttpRoute(
			  name: "default",
			  routeTemplate: "api/{controller}/{action}/{id}",
			  defaults: new { controller = "Home", id = RouteParameter.Optional });
			HttpSelfHostServer server = new HttpSelfHostServer(_config);
			server.OpenAsync().Wait();
			return server;
		}
		public void Start()
		{
			_HTTPserver = CreateHost();
		}
		public void Stop()
		{
			if (_HTTPserver != null)
				_HTTPserver.CloseAsync().Wait();
		}
	}


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

DefaultAssembliesResolver


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 контроллерами */);
			assemblies.Add(Assembly.LoadFrom(path));
			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
	{
		[HttpGet]
		public object hello()
		{
			return "Hello page";
		}
                [HttpPost]
		public object SendData(int data)
		{
			return new HttpResponseMessage(HttpStatusCode.OK);
		}
       }


Let's pay attention to the line again:

"api/{controller}/{action}/{id}"


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:

Users
Regions
Devices
, 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 0.8.4.10 .

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

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

Also popular now: