With the release of
ASP.NET WebAPI , developers have the opportunity to quickly create REST services in a convenient way, on the one hand fully implementing the principles of REST, and on the other using the full power of the ASP.NET platform.
A lot of articles have already been written about the possibilities and use of WebAPI, for example, you can learn about the interesting
self-documenting function of the service API via ApiExplorer.
There is another great feature of WebAPI, about which not much has been written - the ability of WebAPI to carry out self-hosting service. This article uses an example to figure out how to create and run REST selfhosting services based on WebAPI.
')
REST service self hosting
To provide access to the service API, it is not always advisable to deploy it based on IIS server. If the service is not part of any web application, it makes sense to run it on the basis of its own infrastructure.
Another option to use the self hosting mechanism may be to start services on platforms that do not have an IIS server or on which launching IIS is difficult or unnecessary.
Anyway, WebAPI allows you to create services independent of IIS, access to which can be obtained without installing a web application on a web server.
Service inside the console application
Consider the function of self-hosting on the simplest example of a console application. Create a C # based template console application in Visual Studio 2012.
Using the NuGet Batch Manager Console, install the AspNetWebApi.Selfhost package. This can be done with the following command:
Install-package AspNetWebApi.Selfhost
This command will install all necessary components in the project of the console application. After that, add a link to the System.Web assembly to the project, if there is no such link yet.
The first step to create a selfhosting service is to configure it. The HttpSelfHostConfiguration class is responsible for configuring. Below is an example of configuring a service:
var selfHostConfiguraiton = new HttpSelfHostConfiguration("http://localhost:5555"); selfHostConfiguraiton.Routes.MapHttpRoute( name: "DefaultApiRoute", routeTemplate: "api/{controller}", defaults: null );
The first line creates an instance of the server class with the specified address. The second line configures the server's routing mechanism so that we can run our own REST API on it.
The next step is to start the server, this is achieved using another class HttpSelfHostServer. Below is the code that starts the server for selfhosting services:
using (var server = new HttpSelfHostServer(selfHostConfiguraiton)) { server.OpenAsync().Wait(); Console.ReadLine(); }
It's time to add a REST service to our application that will be hosted on our server. To do this, add a new Web API Controller Class element to the project, for example, with the name ProductController. Add a new class named Product to the project:
public class Product { public int ID { get; set; } public string Name { get; set; } public string Description { get; set; } }
In the newly created ProductController controller, add a new method GetAllProducts:
public IList<Product> GetAllProducts() { return new List<Product>(){ new Product(){ID = 1, Name="Product 1", Description="Desc 1"}, new Product(){ID = 2, Name="Product 2", Description="Desc 2"}, new Product(){ID = 3, Name="Product 3", Description="Desc 3"}, }; }
In order to avoid conflicts, you will need to delete or comment out the Get () method generated in the template.
Due to the fact that our application will be a server that listens to certain ports, the application must be running with elevated privileges. You can run the compiled executable file as an administrator on your own or run the project for execution in VS2012 running as an administrator. Another option would be to use the Netsh.exe command to grant permissions to reserve the URL to the current user.
Run the application for execution.
Now, while our application is running, we can access the selfhosting service, which is launched without using IIS. Just go to
http: // localhost: 5555 / api / product / . For testing, you can use the browser or use Fiddler (Figure 1).

Fig.1. Result of accessing the selfhosting service
Starting selfhosting services as a Windows service
To start a selfhosting service, launching an application server as a Windows service is a good idea. Make it simple enough.
A very convenient TopShelf tool can be used to quickly create system services. In the NuGet package manager console, execute the package installation command:
install-package topshelf
After installing the package, you will get access to the API, which allows you to easily create a Windows service from your application.
Let's a little change the code of our project. First, we will launch the server into a separate class ProductService:
class ProductService { private readonly HttpSelfHostServer server; public ProductService() { var selfHostConfiguraiton = new HttpSelfHostConfiguration("http://127.0.0.1:5555"); selfHostConfiguraiton.Routes.MapHttpRoute( name: "DefaultApiRoute", routeTemplate: "api/{controller}", defaults: null ); server = new HttpSelfHostServer(selfHostConfiguraiton); } public void Start() { server.OpenAsync(); } public void Stop() { server.CloseAsync(); server.Dispose(); } }
Then we modify the code of the Main method to start the service using the TopShelf API:
static void Main(string[] args) { HostFactory.Run(x => { x.Service<ProductService>(s => { s.SetServiceName("ProductService Example"); s.ConstructUsing(name => new ProductService()); s.WhenStarted(svc => svc.Start()); s.WhenStopped(svc => svc.Stop()); }); x.RunAsLocalSystem(); x.SetDescription("ProductService WebAPI selfhosting Windows Service Example"); x.SetDisplayName("ProductService Example"); x.SetServiceName("ProductService"); }); }
Here, using the special methods that TopShelf offers, we register the service, specifying the class necessary for the launch, its start and stop methods, the given description of the service and its name.
After the necessary modifications compile the project. Now you can run your application as a Windows service, this is done using the command:
WebApiSelfhosting install
The service will be installed (Figure 2).

Fig.2. Installing the Windows service
Now, if you go to the list of Windows system services, you can easily find your application (Figure 3).

Fig.3. Service in system services list
You may need to start your service if it is not running (Figure 4)

Fig.4. Service start
Check the work of the selfhosting service running as a Windows service in Fiddler and make sure that everything works.
To remove the service from the system, use the command:
WebApiSelfhosting uninstall
Conclusion
In this article, we looked at one of the features of ASP.NET WebAPI. With the help of self hosting, which is supported in WebAPI, you can create REST services that do not require an IIS server for their launch and can be started in the environment in which you want.
ASP.NET WebAPI is a new tool available to developers in Visual Studio 2012. You can download a new version of Visual Studio 2012 RC at a special short address:
http://vs2012.ru/ .
The source code for the final project (with all packages and binary components) is available via the link
sdrv.ms/K9F7Hs