Self-Hosting ASP.NET Web API
http://www.piotrwalat.net/hosting-web-api-in-windows-service/
ASP.NET Web API is a framework for building HTTP services that can reach a broad range of clients including browsers, phones and tablets. ASP.NET Web API ships with ASP.NET MVC 4 and is part of the Microsoft web platform.
You can read more about Web API in my earlier article @ http://theshravan.net/say-hello-to-asp-net-web-api/
As I mentioned earlier ASP.NET Web API ships with ASP.NET MVC 4. But we are not limited to hosting Web APIs in IIS. ASP.NET Web API gives you the flexibility to host your Web APIs anywhere you would like, including self-hosting in our own process (e.g.: Wpf Application , Console Application, etc…).
In this article I am going explain how to Self-Host Web API in a Console Application and consume from a client application. Same code we can use for Self-Host Web API in any our own process (any application).
To self-host a Web API first we need to setup server configuration, Here are the steps for server configuration:
- Specify the base address for your HTTP server (using HttpSelfHostConfiguration class)
- Configure Http routes for your web APIs
Configuring routes is same as using ASP.NET Routing, But only thing is the routes need to be added to the route collection on ourHttpSelfHostConfiguration instance created in first step.
I am creating a Console Application using Visual Studio. Let’s have a look at project structure in solution explorer.
This is plain vanilla Console Application , We need following important assemblies to work with Web API.
-
System.Web.Http.dll
- The core runtime assembly for ASP.NET Web API
-
System.Net.Http.dll
- Provides a programming interface for modern HTTP applications. This includes HttpClient for sending requests over HTTP, as well as HttpRequestMessage and HttpResponseMessage for processing HTTP messages
-
System.Net.Http.WebRequest.dll
- Provides additional classes for programming HTTP applications
-
System.Web.Http.SelfHost.dll
- Contains everything you need to host ASP.NET Web API within your own process (outside of IIS)
-
System.Net.Http.Formatting.dll
- Adds support for formatting and content negotiation to System.Net.Http. It includes support for JSON, XML, and form URL encoded data
-
Newtonsoft.Json.dll
- Dependent library for System.Net.Http.Formatting.dll to include support for JSON
I grabbed all the above assemblies & add to my project using nuget.
I am creating my Web API controller under Api folder in project (you can place it any where in the project).
using System.Web.Http; namespace WebAPISelfHostSample.Api { public class HelloWorldController : ApiController { public string Get() { return "Hi!, Self-Hosted Web Api Application Get()"; } public string Get(int id) { return "Hi!, Self-Hosted Web Api Application Get() With Id: " + id; } } }
Let’s write code in Program .cs for creating Self-Hosting Web API.
using System; using System.Web.Http; using System.Web.Http.SelfHost; namespace WebAPISelfHostSample { class Program { static void Main(string[] args) { var baseAddress = "http://localhost:8080/"; var config = new HttpSelfHostConfiguration(baseAddress); config.Routes.MapHttpRoute( name : "DefaultApi", routeTemplate : "api/{controller}/{id}", defaults : new { id = RouteParameter.Optional }); Console.WriteLine("Instantiating The Server..."); using (var server = new HttpSelfHostServer(config)) { server.OpenAsync().Wait(); Console.WriteLine("Server is Running Now... @ " + baseAddress); Console.ReadLine(); } } } }
Now Build & Run the Application (Hit F5 – Make sure Visual Studio is running under Administrator , other we will get an exception).
We are Successfully Self-Hosted the Hello World Web Api & The Server is up & running now.
Let’s create client to test this, here is the client code:
using System; using System.Net.Http; namespace SelfHostWebApiClient { class Program { static void Main(string[] args) { var baseAddress = "http://localhost:8080/"; var client = new HttpClient { BaseAddress = new Uri(baseAddress) }; Console.WriteLine("Client received: {0}", client.GetStringAsync("api/helloworld").Result); Console.WriteLine("Client received: {0}", client.GetStringAsync("api/helloworld/10").Result); Console.ReadLine(); } } }
Result:
We are successfully able to access Self-Hosted Web Api from our client application. We can Self Host any complex Web API.
--------------------------------寄宿windowns 服务------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Reflection;
using System.IO;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Dispatcher;
using System.Web.Http.SelfHost;
namespace WebAPISelfHost
{
public partial class Service1 : ServiceBase
{
static HttpSelfHostServer CreateHost(string address)
{
// Create normal config
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address);
config.Routes.MapHttpRoute(
name: "default",
routeTemplate: "api/{controller}/{id}",
defaults: new { controller = "Home", id = RouteParameter.Optional });
HttpSelfHostServer server = new HttpSelfHostServer(config);
server.OpenAsync().Wait();
return server;
}
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
HttpSelfHostServer server = CreateHost("http://localhost:8080");
}
protected override void OnStop()
{
}
}