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. However, this does not mean that you are limited to hosting your web APIs in IIS! ASP.NET Web API gives you the flexiblity to host your web APIs anywhere you would like, including self-hosting in your own process.
Note: This sample uses the NuGet package restore feature to install the required set of NuGet packages when the sample is first built. Make sure you have network access to the public NuGet feed on www.nuget.org before building this sample the first time.
To self-host a web API you first need to setup your server configuration. At a minimum you need to specify the base address for your HTTP server and configure routes for your web APIs. Note that you configure your routes just like you would using ASP.NET Routing, except the routes need to be added to the route collection on your config instance
// Set up server configuration
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Set up server configuration HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );
Implement your web API just like you would if it was web hosted by deriving from ApiController and adding your actions. Here we add a simple HelloController with a Get action that returns a simple string:
public class HelloController : ApiController
{
public string Get()
{
return "Hello, world!";
}
}
public class HelloController : ApiController { public string Get() { return "Hello, world!"; } }
// Create server
server = new HttpSelfHostServer(config);
// Start listening
server.OpenAsync().Wait();
Console.WriteLine("Listening on " + _baseAddress);
// Create server server = new HttpSelfHostServer(config); // Start listening server.OpenAsync().Wait(); Console.WriteLine("Listening on " + _baseAddress);
// Call the web API and display the result
HttpClient client = new HttpClient();
client.GetStringAsync(_address).ContinueWith(
getTask =>
{
if (getTask.IsCanceled)
{
Console.WriteLine("Request was canceled");
}
else if (getTask.IsFaulted)
{
Console.WriteLine("Request failed: {0}", getTask.Exception);
}
else
{
Console.WriteLine("Client received: {0}", getTask.Result);
}
});
// Call the web API and display the result HttpClient client = new HttpClient(); client.GetStringAsync(_address).ContinueWith( getTask => { if (getTask.IsCanceled) { Console.WriteLine("Request was canceled"); } else if (getTask.IsFaulted) { Console.WriteLine("Request failed: {0}", getTask.Exception); } else { Console.WriteLine("Client received: {0}", getTask.Result); } });
When you run the application you should see the result displayed: