- Host ASP.NET Web API, using OWIN to self-host
- Host ASP.NET Web API in an Azure Worker Role
OWIN stands for Open Web Interface for .NET
Step1: Create a Console Application called OWINSelfHostingWebAPI
Step2: Install the WebAPI OWIN selfhost package and all the required OWIN packages using NuGet Package Manager Console.
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
Step3: Configure Web API for self-host.
In Solution Explorer, right-click the project and select Add / Class to add a new class. Name the class Startup and add the below code.
using Owin;
using System.Web.Http;
namespace OwinSelfhostSample
{
public class Startup
{
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
}
Step4: Start the OWIN Host and Make a Request Using HttpClient. Replace all the code in the Program.cs file with the following:
using Microsoft.Owin.Hosting;
using System;
using System.Net.Http;
namespace OwinSelfhostSample
{
public class Program
{
static void Main()
{
string baseAddress = "http://localhost:9000/";
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
// Create HttpCient and make a request to api/values
HttpClient client = new HttpClient();
var response = client.GetAsync(baseAddress + "api/values").Result;
Console.WriteLine(response);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
Console.ReadLine();
}
}
}
}
Step5: Add a web API controller in your solution named value controller.
using System.Collections.Generic;
using System.Web.Http;
namespace OwinSelfhostSample
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
Step6: Run the application.
No comments:
Post a Comment