Monday, 31 December 2018

How to Deploy and Host ASP.Net Web API ?


  1. Host ASP.NET Web API, using OWIN to self-host
  2. 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.






How to return HttpResponseException using HttpError ?

we can use HttpResponseException to return an HttpError:

public Employee GetEmployee(int empid) { Employee emp= repository.Get(empid); if (emp== null) { var message = string.Format("Employee with id = {0} not found", empid); throw new HttpResponseException( Request.CreateErrorResponse(HttpStatusCode.NotFound, message)); } else { return emp; } }

How to handle Model Validation using HttpError ?

For model validation, pass the model state to CreateErrorResponse as follows:

public HttpResponseMessage PostEmployee(Employee emp) { if (!ModelState.IsValid) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } }

How to handle errors using HttpError?

CreateErrorResponse is an extension method defined in the System.Net.Http.HttpRequestMessageExtensions class. Internally, CreateErrorResponse creates an HttpError instance and then creates an HttpResponseMessage that contains the HttpErrorThe HttpError object provides a consistent way to return error information in the response body.

public HttpResponseMessage GetEmployee(int Empid) { Employee emp = repository.Get(Empid); if (emp == null) { var message = string.Format("Employee with Empid = {0} not found", Empid); return Request.CreateErrorResponse(HttpStatusCode.NotFound, message); } else { return Request.CreateResponse(HttpStatusCode.OK, emp); } }

How to Register Exception Filters?

We can register a Web API exception filter:
  • By action
  • By controller
  • Globally
To apply the exception filter to a controller action method:
public class EmployeeController : ApiController { [NotImplExceptionFilter] public Address GetAddress(int id) { throw new NotImplementedException("This method is not implemented"); } }
To apply the exception filter to a controller class:
[NotImplExceptionFilter]
public class EmployeeController : ApiController { public Address GetAddress(int id) { throw new NotImplementedException("This method is not implemented"); } }
To apply the exception filter globally to all Web API controllers:
public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
 
            // Web API routes
 
            config.Filters.Add(new EmployeeDemoProject.NotImplExceptionFilterAttribute());
 
            config.MapHttpAttributeRoutes();
 
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

What are Exception Filters?

HttpResponseException cannot handle all type of errors. It is only designed for handling specifically for returning an HTTP response. An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception.

Acton Filters are present in System.Web.Http.Filters.IExceptionFilter interface and we can override the OnException method of System.Web.Http.Filters.ExceptionFilterAttribute class and put our own implementations.

The Response property of the HttpActionExecutedContext object contains the HTTP response message that will be sent to the client. Below is the example:

namespace EmployeeDemo.Filters { using System; using System.Net; using System.Net.Http; using System.Web.Http.Filters; public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { if (context.Exception is NotImplementedException) { context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented); } } } }