Web API 2 Self Hosting Using OWIN
19:23Introduction
OWIN stands for Open Web Interface for .Net. In this article I want to show how to use Web API 2 self hosting using OWIN.What Is OWIN
OWIN defines a standard interface between .NET servers and applications. The goal of the OWIN interface is to decouple server and application.Why OWIN
OWIN ideal for self-hosting a application in our own process, outside of IIS.Katana
Katana is an open source project by the Microsoft Open Technologies. It is a set of components for building and hosting OWIN-based applications that follows the OWIN specification.Step By Step To Create Application
Startup.cs
using Owin; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Http; namespace Web_API_Self_Hosting_Using_OWIN { class Startup { // This method is required by Katana: public void Configuration(IAppBuilder app) { var webApiConfiguration = ConfigureWebApi(); // Use the extension method provided by the WebApi.Owin library: app.UseWebApi(webApiConfiguration); } private HttpConfiguration ConfigureWebApi() { var config = new HttpConfiguration(); config.Routes.MapHttpRoute( "DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional }); return config; } } }
Product.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Web_API_Self_Hosting_Using_OWIN { public class Product { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public decimal Price { get; set; } } }
TestAPIController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Web.Http; namespace Web_API_Self_Hosting_Using_OWIN { public class TestAPIController : ApiController { private static Listdb = new List { new Product { Id = 1, Name = "Monitor", Category = "Hardware", Price = 10000 }, new Product { Id = 2, Name = "Mouse", Category = "Hardware", Price = 1000 }, new Product { Id = 3, Name = "Keyboard", Category = "Hardware", Price = 500 } , new Product { Id = 4, Name = "VisualStudio", Category = "Software", Price = 80000 }, new Product { Id = 5, Name = "SqlServer", Category = "Software", Price = 35000 }, new Product { Id = 6, Name = "Oracle", Category = "Software", Price = 40000 } }; public IEnumerable Get() { return db; } public Product Get(int id) { var Product = db.FirstOrDefault(c => c.Id == id); if (Product == null) { throw new HttpResponseException(System.Net.HttpStatusCode.NotFound); } return Product; } public IHttpActionResult Post(Product Product) { if (Product == null) { return BadRequest("Argument Null"); } var ProductExists = db.Any(c => c.Id == Product.Id); if (ProductExists) { return BadRequest("Exists"); } db.Add(Product); return Ok(); } public IHttpActionResult Put(Product Product) { if (Product == null) { return BadRequest("Argument Null"); } var existing = db.FirstOrDefault(c => c.Id == Product.Id); if (existing == null) { return NotFound(); } existing.Name = Product.Name; existing.Category = Product.Category; existing.Price = Product.Price; return Ok(); } public IHttpActionResult Delete(int id) { var Product = db.FirstOrDefault(c => c.Id == id); if (Product == null) { return NotFound(); } db.Remove(Product); return Ok(); } } }
ClientHandler.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace Web_API_Self_Hosting_Using_OWIN { class ClientHandler { string _hostUri; public ClientHandler(string hostUri) { _hostUri = hostUri; } public HttpClient CreateClient() { var client = new HttpClient(); client.BaseAddress = new Uri(new Uri(_hostUri), "api/TestAPI/"); return client; } public IEnumerableGetCompanies() { HttpResponseMessage response; using (var client = CreateClient()) { response = client.GetAsync(client.BaseAddress).Result; } var result = response.Content.ReadAsAsync >().Result; return result; } public Product GetProduct(int id) { HttpResponseMessage response; using (var client = CreateClient()) { response = client.GetAsync(new Uri(client.BaseAddress, id.ToString())).Result; } var result = response.Content.ReadAsAsync ().Result; return result; } public System.Net.HttpStatusCode AddProduct(Product Product) { HttpResponseMessage response; using (var client = CreateClient()) { response = client.PostAsJsonAsync(client.BaseAddress, Product).Result; } return response.StatusCode; } public System.Net.HttpStatusCode UpdateProduct(Product Product) { HttpResponseMessage response; using (var client = CreateClient()) { response = client.PutAsJsonAsync(client.BaseAddress, Product).Result; } return response.StatusCode; } public System.Net.HttpStatusCode DeleteProduct(int id) { HttpResponseMessage response; using (var client = CreateClient()) { response = client.DeleteAsync(new Uri(client.BaseAddress, id.ToString())).Result; } return response.StatusCode; } } }
Program.cs
using Microsoft.Owin.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.SelfHost; namespace Web_API_Self_Hosting_Using_OWIN { class Program { static void Main(string[] args) { // Base URL string url = "http://localhost:9000"; // Calling Handler var ProductClient = new ClientHandler(url); Console.WriteLine("Read all the products..."); // Start using (WebApp.Start(url: url)) { var companies = ProductClient.GetCompanies(); WriteCompaniesList(companies); // Get Id int nextId = (from c in companies select c.Id).Max() + 1; // Add Console.WriteLine("Add a new Product..."); var result = ProductClient.AddProduct( new Product { Id = nextId, Name = "UPS", Category = "Hardware", Price = 2500 }); WriteStatusCodeResult(result); // Update After Add Console.WriteLine("Updated List after Add:"); companies = ProductClient.GetCompanies(); WriteCompaniesList(companies); // Update Console.WriteLine("Update a Product..."); var updateMe = ProductClient.GetProduct(nextId); updateMe.Name = string.Format("Updated Name UPS", updateMe.Id); updateMe.Category = string.Format("Updated Category Hardware", updateMe.Id); updateMe.Price = 3000; result = ProductClient.UpdateProduct(updateMe); WriteStatusCodeResult(result); // Update List After Update Console.WriteLine("Updated List after Update:"); companies = ProductClient.GetCompanies(); WriteCompaniesList(companies); // Delete Product Console.WriteLine("Delete a Product..."); result = ProductClient.DeleteProduct(nextId); WriteStatusCodeResult(result); // Update List After Delete Console.WriteLine("Updated List after Delete:"); companies = ProductClient.GetCompanies(); WriteCompaniesList(companies); } Console.ReadLine(); } static void WriteCompaniesList(IEnumerable companies) { try { foreach (var Product in companies) { Console.WriteLine("Id: {0}, Name: {1}, Category: {2}, Price: {3}", Product.Id, Product.Name, Product.Category, Product.Price); } Console.WriteLine(""); } catch (Exception) { throw; } } static void WriteStatusCodeResult(System.Net.HttpStatusCode statusCode) { if (statusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine("Opreation Succeeded - status code {0}", statusCode); } else { Console.WriteLine("Opreation Failed - status code {0}", statusCode); } Console.WriteLine(""); } } }
0 comments