Showing posts with label WCF and WebAPI. Show all posts
Showing posts with label WCF and WebAPI. Show all posts

Monday, June 11, 2018

[Fiddler] The connection to com failed.

Error-Messages

[Fiddler] The connection to '<the site>.com' failed. 
System.Security.SecurityException Failed to negotiate HTTPS connection with server.fiddler.network.https> HTTPS handshake to <the site>.com (for #3) failed. System.IO.IOException Unable to read data from the transport connection: 
An existing connection was forcibly closed by the remote host. < An existing connection was forcibly closed by the remote host 


Resolution - 

Go to  Tools > Telerik Fiddler Options > HTTPS It's set to ;ssl3;tls1.0 Add tls1.2

Kinldy refer below image for reference.


image

Warm Regards

Sachin Kalia

Friday, December 15, 2017

ASP. Net WebAPI With. Net Core & Micro Services

Join Me in GuruGram(Gurgaon) in IKeva to learn

ASP. Net WebAPI With. Net Core & Micro Services

Image may contain: 3 people, people smiling, text

Warm Regards

Sachin Kalia

Tuesday, April 25, 2017

Exclude controllers methods from docs or swagger

Exclude controllers methods from docs or swagger

If you would like to ignore controller’s action method from documentation or swagger ,kindly out an annotation just above an action method.

 [ApiExplorerSettings(IgnoreApi = true)]

Thanks

Wednesday, October 26, 2016

Developing Book My Seat Application In AngularJS And ASP.NET - WebAPI Methods - Part Two

Here, I’ve merely thought to write my thoughts about hands-on Angular. This is my first article which tells you how to get your hands dirty with AngularJS & ASP.NET WEBAPI and SQL Server BookMySeat Application Tutorials.

This is the technology stack for this BookMySeat library application, as shown below:

In the first article, I shared the technology and other brief information about components used. In this article, will look into WebApi creation and route to configure that.
This is an initial look at the WebAPI controller defined in Solution Explorer as depicted below:

If you open this file, you will have around 6 methods which have generic names to perform the operations and easy to understand.These WebAPI methods are given below:




The complete code for all APIs is given below.

  1. public class BookMySeatAPIController : ApiController 
  2.     { 
  3. //
  4. // GET: /BookMySeatAPI/
  5.         SqlConnection objConnection = new SqlConnection(); 
  6. public void SqlConnection() 
  7.         { 
  8.             objConnection.Dispose(); 
  9.             objConnection.ConnectionString = "server=.;database=BookMySeat;uid=sa;pwd=Tpg@1234;"; 
  10.             objConnection.Open(); 
  11.         } 
  12.         [HttpGet] 
  13. public int[] GetSeatCount([FromUri] int slot) 
  14.         { 
  15. try
  16.             { 
  17.                 SqlConnection(); 
  18.                 SqlCommand SqlCommand = new SqlCommand("sp_GetMySeat", objConnection); 
  19.                 SqlCommand.CommandType = CommandType.StoredProcedure; 
  20.                 SqlCommand.Parameters.AddWithValue("@timeslotid", slot); 
  21.                 SqlDataAdapter da = new SqlDataAdapter(SqlCommand); 
  22.                 da.SelectCommand = SqlCommand; 
  23.                 DataSet ds = new DataSet(); 
  24.                 da.Fill(ds); 
  25. int[] result = new int[ds.Tables[0].Rows.Count]; 
  26. for (int i = 0; i < ds.Tables[0].Rows.Count; i++) 
  27.                 { 
  28.                     result[i] = Convert.ToInt16(ds.Tables[0].Rows[i][0].ToString()); 
  29.                 } 
  30. return result; 
  31.             } 
  32. finally
  33.             { 
  34.                 objConnection.Close(); 
  35.                 objConnection.Dispose(); 
  36.             } 
  37.         } 
  38.         [HttpPost] 
  39.         [ActionName("SeatBook")] 
  40. public int[] PostBookSeat(BookSeat objBookSeat) 
  41.         { 
  42. try
  43.             { 
  44.                 SqlConnection(); 
  45.                 SqlCommand SqlCommand = new SqlCommand("sp_BookMySeat", objConnection); 
  46.                 SqlCommand.CommandType = CommandType.StoredProcedure; 
  47.                 SqlCommand.Parameters.AddWithValue("@UserName", objBookSeat.UserName); 
  48.                 SqlCommand.Parameters.AddWithValue("@TimeSlot", objBookSeat.TimeSlot); 
  49.                 SqlCommand.Parameters.AddWithValue("@SeatNo", objBookSeat.SeatNo); 
  50.                 SqlDataAdapter da = new SqlDataAdapter(SqlCommand); 
  51.                 da.SelectCommand = SqlCommand; 
  52.                 DataSet ds = new DataSet(); 
  53.                 da.Fill(ds); 
  54. int[] result = new int[ds.Tables[0].Rows.Count]; 
  55. for (int i = 0; i < ds.Tables[0].Rows.Count; i++) 
  56.                 { 
  57.                     result[i] = Convert.ToInt16(ds.Tables[0].Rows[i][0].ToString()); 
  58.                 } 
  59. return result; 
  60.             } 
  61. finally
  62.             { 
  63.                 objConnection.Close(); 
  64.                 objConnection.Dispose(); 
  65.             } 
  66.         } 
  67.         [HttpPost] 
  68.         [ActionName("ValidateUser")] 
  69. public string ValidateUser(ValidateUser objValidateUser) 
  70.         { 
  71. try
  72.             { 
  73.                 SqlConnection(); 
  74.                 SqlCommand SqlCommand = new SqlCommand("ValidateUser", objConnection); 
  75.                 SqlCommand.CommandType = CommandType.StoredProcedure; 
  76.                 SqlCommand.Parameters.AddWithValue("@UserName", objValidateUser.UserName); 
  77.                 SqlDataAdapter da = new SqlDataAdapter(SqlCommand); 
  78.                 da.SelectCommand = SqlCommand; 
  79.                 DataSet ds = new DataSet(); 
  80.                 da.Fill(ds); 
  81. return ds.Tables[0].Rows[0][0].ToString(); 
  82.             } 
  83. finally
  84.             { 
  85.                 objConnection.Close(); 
  86.                 objConnection.Dispose(); 
  87.             } 
  88.         } 
  89.         [HttpPost] 
  90.         [ActionName("SeatDetail")] 
  91. public string GetSeatDetail(GetSeatDetail objGetSeatDetail) 
  92.         { 
  93. try
  94.             { 
  95.                 SqlConnection(); 
  96.                 SqlCommand SqlCommand = new SqlCommand("sp_GetSeatDetail", objConnection); 
  97.                 SqlCommand.CommandType = CommandType.StoredProcedure; 
  98. // SqlCommand.Parameters.AddWithValue("@UserName", objBookSeat.UserName);
  99.                 SqlCommand.Parameters.AddWithValue("@TimeSlot", objGetSeatDetail.TimeSlot); 
  100.                 SqlCommand.Parameters.AddWithValue("@SeatNo", objGetSeatDetail.SeatNo); 
  101.                 SqlDataAdapter da = new SqlDataAdapter(SqlCommand); 
  102.                 da.SelectCommand = SqlCommand; 
  103.                 DataSet ds = new DataSet(); 
  104.                 da.Fill(ds); 
  105. return ds.Tables[0].Rows[0][0].ToString(); 
  106.             } 
  107. finally
  108.             { 
  109.                 objConnection.Close(); 
  110.                 objConnection.Dispose(); 
  111.             } 
  112.         } 
  113.         [HttpPost] 
  114.         [ActionName("DeleteSeat")] 
  115. public string DeleteSeat(DeleteSeat objDeleteSeat) 
  116.         { 
  117. try
  118.             { 
  119.                 SqlConnection(); 
  120.                 SqlCommand SqlCommand = new SqlCommand("sp_DeleteSeat", objConnection); 
  121.                 SqlCommand.CommandType = CommandType.StoredProcedure; 
  122. // SqlCommand.Parameters.AddWithValue("@UserName", objBookSeat.UserName);              
  123.                 SqlCommand.Parameters.AddWithValue("@SeatNo", objDeleteSeat.SeatNo); 
  124.                 SqlCommand.Parameters.AddWithValue("@SlotNo", objDeleteSeat.TimeSlot); 
  125.                 SqlDataAdapter da = new SqlDataAdapter(SqlCommand); 
  126.                 da.SelectCommand = SqlCommand; 
  127.                 DataSet ds = new DataSet(); 
  128.                 da.Fill(ds); 
  129. return ds.Tables[0].Rows[0][0].ToString(); 
  130.             } 
  131. finally
  132.             { 
  133.                 objConnection.Close(); 
  134.                 objConnection.Dispose(); 
  135.             } 
  136.         } 
  137.         [HttpGet] 
  138. public List<ShowBookSeat> ShowBookSeat() 
  139.         { 
  140. try
  141.             { 
  142.                 SqlConnection(); 
  143.                   List<ShowBookSeat> list = new List<ShowBookSeat>();  
  144.                 SqlCommand SqlCommand = new SqlCommand("sp_ShowBookDetail", objConnection); 
  145.                 SqlCommand.CommandType = CommandType.StoredProcedure; 
  146. // SqlCommand.Parameters.AddWithValue("@UserName", objBookSeat.UserName);              
  147. //SqlCommand.Parameters.AddWithValue("@UserName", objDeleteSeat.SeatNo);
  148. //SqlCommand.Parameters.AddWithValue("@SlotNo", objDeleteSeat.TimeSlot);
  149.                 SqlDataAdapter da = new SqlDataAdapter(SqlCommand); 
  150.                 da.SelectCommand = SqlCommand; 
  151.                 DataSet ds = new DataSet(); 
  152.                 da.Fill(ds); 
  153. for (int i = 0; i < ds.Tables[0].Rows.Count; i++) 
  154.                 { 
  155.                     ShowBookSeat ShowBookSeat = new ShowBookSeat(); 
  156.                     ShowBookSeat.UserName = (ds.Tables[0].Rows[i]["username"]).ToString(); 
  157.                     ShowBookSeat.Date =Convert.ToDateTime(ds.Tables[0].Rows[i]["currentday"]); 
  158.                     ShowBookSeat.TimeSlot = Convert.ToInt32(ds.Tables[0].Rows[i]["timeslot"]); 
  159.                     ShowBookSeat.SeatNo = Convert.ToInt32(ds.Tables[0].Rows[i]["seatno"]); 
  160.                     list.Add(ShowBookSeat); 
  161.                 } 
  162. return list;  
  163.             } 
  164. finally
  165.             { 
  166.                 objConnection.Close(); 
  167.                 objConnection.Dispose(); 
  168.             } 
  169.         } 
  170.     } 

Code segment for WebApiConfig under App_start folder is given below.

  1. public static class WebApiConfig 
  2.     { 
  3. public static void Register(HttpConfiguration config) 
  4.         { 
  5.             config.Routes.MapHttpRoute( 
  6.                 name: "DefaultApi", 
  7.                 routeTemplate: "api/{controller}/{id}", 
  8.                 defaults: new { id = RouteParameter.Optional } 
  9.             ); 
  10.             config.Routes.MapHttpRoute( 
  11.                name: "seatbook", 
  12.                routeTemplate: "api/seat/{controller}/{action}/{id}", 
  13.                defaults: new { id = RouteParameter.Optional } 
  14.            ); 
  15.             config.Routes.MapHttpRoute( 
  16.                name: "seatDetail", 
  17.                routeTemplate: "api/seatdetail/{controller}/{action}/{id}", 
  18.                defaults: new { id = RouteParameter.Optional } 
  19.            ); 
  20.             config.Routes.MapHttpRoute( 
  21.                name: "ValidateUser", 
  22.                routeTemplate: "api/ValidateUser/{controller}/{action}/{id}", 
  23.                defaults: new { id = RouteParameter.Optional } 
  24.            ); 
  25.             config.Routes.MapHttpRoute( 
  26.                name: "DeleteSeat", 
  27.                routeTemplate: "api/DeleteSeat/{controller}/{action}/{id}", 
  28.                defaults: new { id = RouteParameter.Optional } 
  29.            ); 
  30.         } 
  31.     } 

The application which we are about to build consists almost all of the above defined keywords and the initial look of the application is as shown below.

Hope it’ll help you some day. Enjoy Coding.

Wednesday, October 19, 2016

BOOKMYSEAT APPLICATION AngularJS  Asp.Net Webapi and Sql Server 2012

Here, I’ve thought to write my thoughts about hands-on Angular. This is the first article, which tells you  how to get your hands dirty with AngularJS, ASP.NET WEBAPI and SQL Server BookMySeat Application Tutorials.
This is the technology stack for BookMySeat library Application, as shown below:



I’ve designed a simple BookMySeat Library Application, where you will be familiarized with a few keywords & components, which you may be confronting in coming days. These keywords are shown below in the article-

Component of Angular Description

Module
Modules serve as containers to assist you to organize the code within your AngularJS Application. Modules can contain sub-modules.

$http
$http is an AngularJS Service for reading the data from the remote Servers.

Angular ui.bootstrap
<scriptdata-require="ui-bootstrap@*"data-semver="0.10.0"src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.10.0.js"></script>

Services
Services are a point, where you can put common functionality to an AngularJS Application. For example,  if you would like to share the data with more than one controller then the best way is to promote the data to the Service and then make it available via the Service. Services extend the controllers and make them more globally accessible.

Routes Routing in Angular JS
Routes allow us to determine the ways to navigate to the specific states within our Application. It also allows us to define the configuration options for each specific route, such as which template and controller to use.

View
The view in AngularJS is what exists after AngularJS has compiled and rendered the DOM.

@scope
$scope is essentially the “glue” between the view and controller within an AngularJS Application. It supports two way binding within an Application.

Controller
The controller is to define the methods and properties that the view can bind to and interact with. Controllers should be lightweight and only focus on the view; they’re controlling.

Directive
A directive is an extension of a view in AngularJS, which allows us to create custom, reusable elements. You can also consider the directives as the decorators for your HTML. Directives are used to extend the views and to make these extensions available for use in more than one place.

Route Config
The config block of an AngularJS Application allows for the configuration to be applied before the Application actually runs. This is useful to set up routes, dynamically configuring Services and so on.

Dependency Injection
How can we inject dependency in Angular controller and module? For this sample Application, we have injected $Log,$RouteParams,$modal ,Custom Services and many more.

The Application which we are about to build consists of almost all the defined keywords, mentioned above and the initial look of the application is shown below-

There are a few points which we’ll cover in this Application. To make it complete, you can also reference how this Application will work from this BookMySeat Gif representation,

  • The screenshot, shown above, is a sample form for BookMySeat Application .You can book your seat for the specific slot. You can cancel your seat also from the given slot.
  • In the same way, we’ll try to integrate UI-bootstrap (modal Popup) to show which seat is booked by the user.
  • We will focus on Custom Directive and Custom Service.
  • Usage of $http to call to WebApi to populate the data on HTML page.
  • Usage of dependency injection at the various levels, Load partial templates to MVC view page.
  • There can be some various add ons, which you can do at your level after the completion of this Application like Email notification after booking the seat, cancel the seat, booking slot information and responsive Application .
  • The structure of the BookMySeat Application is given below-

    The basic life cycle of Angular app is given below-
Hope it’ll help you some day. Enjoy coding.

Wednesday, September 21, 2016

 Bookmyseat application angularjs ,webapi and sqlserver 2008 using angular ui bootstrap

Hi Folks,

I have created a bookmyseat application which has the following technology stack.

  • AmgularJS (  Angular Module,Controller,Angular Service, Routing, Dependancy injection, Service calling using $http.post)
  • Asp.Net WebAPI (Get,Post,Put methods with Routing)
  • SQl Server 2008R2
  • Angular UI-bootstrap UI Bootstrap for PopUp purpose

 

BookMySeat

 

I’ll come with step by step articles day by day.

Thanks

Thursday, July 7, 2016

Web API Pipeline Revealed: A True Practical Approach

Web API Pipeline Revealed: A True Practical Approach

What is WebApi?
This question carries a lot of weight. Web API is a small word but it has lots of extensive features.
Here is an excerpt about Web API:
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. It is an ideal platform for building RESTful applications on the .NET Framework. This poster shows how an HTTP request flows through the Web API pipeline, and how the HTTP response flows back. The diagram also shows extensibility points, where you can add custom code or even replace the default behavior entirely.
This article is about WebApi and its Pipeline. Pipeline in simple words is HttpRequest as pipeline and HttpResponse as an output. Kindly refer to the image below:
pipeline
This will be an agenda for this article as shown below:
  • WebApi Definition.
  • WebApi Pipeline architecture
  • WebApi Hosting
  • WebApi HttpRequest & HttpResponse Message format
  • WebApi Delegate Handler
  • Routing Dispatcher and per-route message handler
  • HttpControllerDispatcher
  • Authentication & Authorization Filters
  • Model Binders, Value Providers and Action Filters
  • IHttpActionInvoker & Exception Filters
  • Result Conversation
Web API Definition
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. It is an ideal platform for building RESTful applications on the .NET Framework. This poster shows how an HTTP request flows through the Web API pipeline, and how the HTTP response flows back. The diagram also shows extensibility points, where you can add custom code or even replace the default behavior entirely.
Web API Architecture Here is typical pipeline architecture for Web API as in the following screenshot:
Architecture
Web API Hosting
You can host Web API inside IIS or inside your own process (self-hosting).
ASP.NET Hosting
You can host Web API on ASP.NET server and IIS server. For more details kindly go through the following details how to host Web API in IIS: WebApi Hosting in Internet Information Server (IIS 7.5).
Self-Hosting using OWIN In Self Hosting you can use OWIN to Self-Host ASP.NET Web API, The HttpServer pipeline starts at the HttpSelfHostServer which is an implementation of HttpServer and directly listens to HTTP requests.
WebApi HttpRequest & HttpResponse Message format The HTTP request message is first converted to an HttpRequestMessage object, which provides strongly typed access to the HTTP message. There are two types of Http messages HttpRequest and HttpResponse. Each of this has their own format before sending it to respective server and received response from server.
The structure of HttpRequestMessage format is as follows with a pictorial representation.
  1. <request-line> 
  2. <general-headers> 
  3. <request-headers> 
  4. <entity-headers> 
  5. <empty-line> 
  6. [<message-body>] 
  7. [<message-trailers>] 
structure
The structure of HttpResponseMessage format is as follows with a pictorial representation.
  1. <Status-line> 
  2. <general-headers> 
  3. <response-headers> 
  4. <entity-headers> 
  5. <empty-line> 
  6. [<message-body>] 
  7. [<message-trailers>] 
structure
This is the way to understand the HttpRequest and HttpResponse messages.
Web API Delegate Handler HTTP message handlers are the first stage in the processing pipeline after the request leaves the service host. Further it travels in pipeline as HttpRequestMessage in Pipeline. They process HTTP request messages on the way in, and HTTP response messages on the way out. To create a custom message handler, derive from the DelegatingHandler class. You can add multiple message handlers. Message handlers can be global or assigned to a specific route and called as per-route message handler. Per-route message handler is invoked only when the request matches that route. Per-route message handlers are configured in the routing table. A message handler can create the response directly, skipping the rest of the pipeline.
Delegate handlers are extensibility points which you can customize as per your need. One of the reasons may be to verify the request authenticity and to verify some potential information in the http request .You may also customize the Http response as well and customize messages. A message handler can create the response directly, skipping the rest of the pipeline. Kindly refer to the below image for reference to register global handler in pipeline. There is an example, how a message handler might help you,
  • Read or modify request headers.
  • Add a response header to responses.
  • Validate requests before they reach the controller.
code
config.MessageHandlers.Add(new CustomHandler_One());
Routing Dispatcher and per-route message handler
After registering global handler and its execution request reaches HttpRouteDispatcher and sends it further in pipeline. HttpRoutingDispatcher dispatches the request based on the route. As per the WebApi Pipeline diagram above HttpRouteDispatcher verifies whether Route handler is null or contains any handler and takes an anticipated action on the basis of that. Delegate handlers give you the privilege to customize the pipeline and allow you to skip the pipeline. You can add a message handler to a specific route when you define the route there i s a typical image which describes multiple handlers globally and per route handler in pipeline.
Reference
diagram
Image Source: asp.net
If you notice in above image that MessageHandler2 doesn’t go to the default HttpControllerDispatcher. Here, MessageHandler2 creates the response, on basis of requests that match "PerRoute" never go to a controller further and skips the pipeline. Kindly refer to the code shown below to register the Per-Route handler in WebApiConfig.cs file as shown below in screen shot and code segment as well.
code
  1. public static class WebApiConfig 
  2. public static void Register(System.Web.Http.HttpConfiguration config)  
  3.   { 
  4.         config.MapHttpAttributeRoutes(); 
  5.         config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new
  6.         { 
  7.             id = RouteParameter.Optional 
  8.         }); 
  9.         config.MessageHandlers.Add(new CustomHandler_One()); 
  10.         config.Routes.MapHttpRoute(name: "PerRoute", routeTemplate: "api2/{controller}/{action}/{id}", defaults: new
  11.             { 
  12.                 id = RouteParameter.Optional 
  13.             }, constraints: null, handler: new CustomHandler_Two() 
  14. //handler: HttpClientFactory.CreatePipeline(
  15. //new HttpControllerDispatcher(config),
  16. //new DelegatingHandler[] { new CustomHandler_Two() })
  17.         ); 
  18.     } 
If you want “PerRoute” handler to execute complete WebApi pipeline as well as further reach to HttpControllerDispatcher then you just require registering PerRoute handler in WebApiConfig as given below in code segment.
  1. public static class WebApiConfig 
  2. public static void Register(System.Web.Http.HttpConfiguration config)  
  3.   { 
  4.         config.MapHttpAttributeRoutes(); 
  5.         config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new
  6.          { 
  7.             id = RouteParameter.Optional 
  8.         }); 
  9.         config.MessageHandlers.Add(new CustomHandler_One()); 
  10.         config.Routes.MapHttpRoute(name: "PerRoute", routeTemplate: "api2/{controller}/{action}/{id}", defaults: new
  11.          { 
  12.                 id = RouteParameter.Optional 
  13.             }, constraints: null, 
  14. // handler: new CustomHandler_Two()
  15.             handler: HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(config), new DelegatingHandler[] 
  16.             { 
  17. new CustomHandler_Two() 
  18.             })); 
  19.     } 
code
HttpControllerDispatcher
HttpControllerDispatcher sends the request to a Web API controller.
HttpControllerDispatcher is related to Delegate handler somewhere because whenever you create any custom handler it calls SendAsync(request, cancellationToken) method which redirects call to inner Handler and generally this inner handler is HttpControllerDispatcher which handles the controller action request. Kindly refer one of the following screen:
table
This is one of the execution flow of HttpRequest starts from HttpMessageHandler till controller descriptor and Action selector as per my understanding as shown below,
image
Authentication & Authorization Filters If I think deeply about an above picture than security is an always a major concern in Web-based applications. You should have proper set of implementation in form of Authenticaiton and authorization technique to secure that data. As you know that ASP.Net Web API is a lightweight framework used for building stateless RESTful services that run on HTTP. There is authentication filter introduced in WebApi2. Authentication filters allows you to create an authentication scheme for individual controllers or actions. Both of these works in a pattern like given below:
  • Authentication proves the identity of the client.
  • Authorization determines whether the client can access a particular resource. To implement Authentication filters class should implement System.Web.Http.Filters.IAuthenticationFilter interface.
The IAuthenticationFilter interface has two methods
  • AuthenticateAsync authenticates the request by validating credentials in the request, if present.
  • ChallengeAsync adds an authentication challenge to the HTTP response, if needed.
Here is the flow in the Web API 2 pipeline using Authentication and Authorization filter
  1. Web API creates an authentication filters before invoking an action. Authentication filter can be apply at action scope, controller scope, and global scope.
  2. Web API calls AuthenticateAsync on every filter. Each filter validates credentials in the request. If any filter successfully validates credentials, the filter creates an IPrincipal and attaches it to the request. If an error occurs at filter level than it skips the rest of the WebApi pipeline.
  3. Suppose if there is no error, the HttpRequest goes and execute through the rest of the pipeline.
  4. Finally, Web API calls every authentication filter’s ChallengeAsync method. Filters use this method to add a challenge to the response, if needed. Sometime it happens in response to a 401 error.
  5. The diagram showed below states a possibility and its execution flow. The authentication filter successfully authenticates the HttpRequest, an authorization filter authorizes the request, and the controller action returns 200 (OK). Reference http://asp.net
    flow
Authentication filter has two methods AuthenticateAsync and ChallengeAsync as shown below in code snippet. The primary purpose of the ChallengeAsync is to manage and add challenge in response. There is a class named as ResultWithChallenge below in code segment which is responsible to call ExecuteAsync and further calls InnerResult. ExecuteAsync to create the HTTP response, and then adds the challenge if needed.
  1. public class CustomAuthenticationFilterAttribute: Attribute, IAuthenticationFilter  
  2.   #region IAuthenticationFilter Members
  3. public System.Threading.Tasks.Task AuthenticateAsync(HttpAuthenticationContext context, System.Threading.CancellationToken cancellationToken) { 
  4. return Task.FromResult(0); 
  5.     } 
  6. public System.Threading.Tasks.Task ChallengeAsync(HttpAuthenticationChallengeContext context, System.Threading.CancellationToken cancellationToken) { 
  7.         context.Result = new CustomResultChallenge(context.Result, "Authentication Failed!!!"); 
  8. return Task.FromResult(0); 
  9.     } 
  10.   #endregion# region IFilter Members
  11. public bool AllowMultiple 
  12.     { 
  13. get
  14.         { 
  15. return false; 
  16.         } 
  17.     }#endregion 
Let’s verify that how does WebApi respond from ChallengeAsync with Unauthorized status. Press F5 and see WebApi is running after getting below screen shot:
web api
Send the Get request in order to verify the execution cycle as given below. Copy and paste the following Url (http://localhost:57888/api/employees/GetEmp/5) in PostMan tool as depicted below in screen shot.
output
As soon as you click on the send button it reaches to Custom value provider’s method to execute set of statement and gives you following output in an image shown below:
output
Model Binders, Value Providers
image
Model binding uses the request to create values for the parameters of the action .These values are passed to the action when the action is invoked or binding is a mechanism used by the WebApi to mapping request to an object defined in the controller. Model binding is the process of creating .NET objects using the data sent by the browser in an HTTP request. We have been relying on the model binding process each time defines an action method that takes a parameter. the parameter objects are created by model binding. Model binding is ASP.NET mechanism for mapping HTTP request data directly into action method parameters and custom .Net objects.
  • For example, when we receive a request for a URL such as "/Home/ Employees/23", the framework must map the details of the request in such a way that it can pass appropriate values or objects as parameters to our action method. A model binder gets raw input values from a value provider and later value provider takes the HTTP request and populates a dictionary of key-value pairs. Further the model binder uses this dictionary to populate the model.
The action invoker, the component that invokes action methods, is responsible for obtaining values for parameters before it can invoke the action method.
Value Providers Value Providers are the components that feed data to model binders. Feeding the data means installing the data to the Model binder for further use at the action level. Value provider takes the HTTP request and populates a dictionary of key-value pairs which is later used by model binder to populate the model.
The framework contains a few built-in value providers named FormValueProvider, RouteDataValueProvider, QueryStringValueProvider and HttpFileCollectionValueProvider that fetch data from Request.Form, Request.QueryString, Request.Files and RouteData.Values.
The code shown below for CustomValueProvider used at this application level as well as way to use it at action level in an image shown below:
  1. public class CustomHeaderValueProvider: IValueProvider 
  2.   #region IValueProvider Members
  3. public Dictionary < string, string > objCollection; 
  4. public CustomHeaderValueProvider(HttpActionContext context)  
  5.     { 
  6.         objCollection = new Dictionary < string, string > (); 
  7. foreach(var item in context.Request.Headers)  
  8.         { 
  9.             objCollection.Add(item.Key, string.Join(string.Empty, item.Value)); 
  10.         } 
  11.     } 
  12. public bool ContainsPrefix(string prefix) 
  13.     { 
  14. return objCollection.Keys.Contains(prefix); 
  15.     } 
  16. public ValueProviderResult GetValue(string key)  
  17.     { 
  18. string resultValue; 
  19. if (key == null) throw new Exception("NullReferenceException"); 
  20. if (objCollection.TryGetValue(key, out resultValue)) 
  21.         { 
  22. return new ValueProviderResult(resultValue, resultValue, System.Globalization.CultureInfo.InvariantCulture); 
  23.         } 
  24. return null; 
  25.     }#endregion 
  26. public class CustomValueProviderFactory: ValueProviderFactory  
  27. public override IValueProvider GetValueProvider(HttpActionContext actionContext) 
  28.     { 
  29. return new CustomHeaderValueProvider(actionContext); 
  30.     } 
code
reminder
At the time of the model binding the DefaultModelBinder checks with the value providers to determine if they can return a value for the parameter (example empId) by calling the ContainsPrefix method. If none of the value providers registered can return then it checks through CustomtvalueProvider whether such a parameter is stored and if yes it returns the value.
This is one of the best pictorial representations taken from http://asp.net site is shown below which is again self-explanatory.
Image taken from http://asp.net
image
Kindly refer this link for more understanding on Model Binder Invoke Action with Model Binders andFetch Header Information Using CustomValueProvider in ASP.NET Web API
IHttpActionInvoker & Action Filters
Once ApiControllerActionInvoker selects an action to handle an HTTP request, and is responsible for producing HttpResponse of your action. The action invoker, the component that invokes action methods, is responsible for obtaining values for parameters before it can invoke the action method. In other words, the invoker gets an instance of HttpActionContext and is expected to produce an HttpResponseMessage out of it. For this purpose it has to invoke an ExecuteAsync method on the
HttpActionDescriptor present on the HttpActionContext Action Invoker can be a point to manage your exception at global level and returns a response on basis of the result returned by action method of controller. There is an interface shown given below to implement custom action invoker which has method to implement as shown below:
  1. public interface IHttpActionInvoker{ 
  2. Task<HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken); 
There can be three possible scenarios which can be maintained at ActionInvoker level,
  1. You action returns an object than it has to convert into HttpResponseMessgae by IActionResultConverter and run content negotiation with the help of request.createResponse().
  2. If action returns IHttpActionResult than it can be convert into HttpResponseMessage at action invoker level. Which gives privilege to mold your response at this level?
  3. It can return HttpResponseMessage directly from action method.
I’ve created Custom action invoker at my application level to achieve Exception Handling after returning result by the action and later apply code at action invoker level to change it into HttpResponseMessege.
  1. public class Custom_ControllerActionInvoker: ApiControllerActionInvoker, IHttpActionInvoker 
  2. public override System.Threading.Tasks.Task < System.Net.Http.HttpResponseMessage > InvokeActionAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken) { 
  3.         var objResult = base.InvokeActionAsync(actionContext, cancellationToken); 
  4.         actionContext.Request.Properties["RuntimeReturnType"] = objResult.GetType(); 
  5. if (objResult.Exception != null)  
  6.         { 
  7.             Debug.WriteLine("Exception thrwon by controller {0} :", actionContext.ControllerContext.Controller); 
  8. return Task.Run < HttpResponseMessage > (() => new HttpResponseMessage(HttpStatusCode.InternalServerError)); 
  9.         } else if (objResult.Result.StatusCode == HttpStatusCode.Forbidden)  
  10.         { 
  11. //Log critical error
  12.             Debug.WriteLine("Exception thrwon by controller {0} :", actionContext.ControllerContext.Controller); 
  13. return Task.Run < HttpResponseMessage > (() => new HttpResponseMessage(objResult.Result.StatusCode)); 
  14.         } 
  15. return objResult; 
  16.     } 
code
Kindly find a screen shot and code segment to register CustomActionInvoker in an application as shown below:
code
  1. GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpActionInvoker), new Custom_ControllerActionInvoker()); 
Action Filters Custom filters and attributes are an excellent way to inject extra processing logic into the MVC request response pipeline. At some level programmer would be happy to inject some pre-processing or post-processing logic for actions and controllers. In that case we use filters.

This filter will be called before and after the action starts executing and after the action has executed. It comes under namespace using System.Web.Http.Filters;
OnActionExecuting occurs just before the action method is called.
OnActionExecuted occurs after the action method is called, but before the result is executed (before the view is rendered).
  1. public class CustomActionWebApiFilters: ActionFilterAttribute  
  2. public override void OnActionExecuting(HttpActionContext actionContext) 
  3.     { 
  4. // pre-processing
  5.         Debug.WriteLine("Action just added pre-processing logging/information..."); 
  6.     } 
  7. public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)  
  8.     { 
  9. //Write your custom logic here
  10.     } 
I’ve also added Exception filter to manage exception at code level an the respective code shown below:
  1. public class CustomExceptionFilterAttribute: ExceptionFilterAttribute 
  2. public override void OnException(HttpActionExecutedContext actionExecutedContext)  
  3.     { 
  4. if (actionExecutedContext.Exception is ArgumentException) 
  5.         { 
  6.             actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented); 
  7.         } 
  8.     } 
Kindly find a way to register an Exception filter in global.asax file as given below as well as uses at controller’s action level.
  1. GlobalConfiguration.Configuration.Filters.Add(new CustomExceptionFilterAttribute()); 
code
reminder
IHttpActionInvoker can be applying to manage Exception at action level.
IHttpActionInvoker can be used to read runtime context sent by action and made further amendment to send it further as HttpResponseMessage.You may learn more about Action filters in WebApi from thislink
Result Conversation
As name implies Result conversation is about to convert return value from action in form of HttpResponseMessege.The result returned by the an action can be in multiple form and those forms are given below with pictorial representation taken from
Image taken from http://asp.net
image
  • HttpResponseMessege: If return type is HttpResponseMessage sent it directly.
  • Void : If return type is void, create response with status 204 (No Content)
  • IHttpActionResult: Call ExecuteAsync to create an HttpResponseMessage, and then convert to an HTTP response message.
  • Other Types: For return types, Web API uses a media formatter to serialize the return value. Web API writes the serialized value into the response body. The response status code is 200 (OK).
IHttpActionResult plays a vital role in HttpResponseMessege category ,because it allows you return your own return set after introducing in WebAPI2 .There are few advantages of IHttpActionResult are listed below:
  • Moves common logic for creating HTTP responses into separate classes. Which makes code readability easier.
  • Makes the controller action clear and concise, by hiding the low-level details of constructing the response.
IHttpActionResult contains a single method, ExecuteAsync, which asynchronously creates an HttpResponseMessege.
  1. public async System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> ExecuteAsync(System.Threading.CancellationToken cancellationToken) 
There is an example of IHttpActionResult which have been used at Authentication Filter level and states that ExecuteAsync just add Header value in response and returns. Please have a quick look at the code shown below.
  1. public class CustomResultChallenge: IHttpActionResult  
  2.   #region IHttpActionResult Members
  3. private readonly IHttpActionResult result; 
  4. private readonly string realm; 
  5. public CustomResultChallenge(IHttpActionResult result, string realm)  
  6.     { 
  7. this.result = result; 
  8. this.realm = realm; 
  9.     } 
  10. public async System.Threading.Tasks.Task < System.Net.Http.HttpResponseMessage > ExecuteAsync(System.Threading.CancellationToken cancellationToken)  
  11.     { 
  12.         var res = await result.ExecuteAsync(cancellationToken); 
  13. if (res.StatusCode == HttpStatusCode.Unauthorized)  
  14.         { 
  15.             res.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Basic", this.realm)); 
  16.         } 
  17. return res; 
  18.     }#endregion 
Kindly see vital point marked yellow in the below screen shot;
code
Press F5 and run you WebApi as depicted below in an image,
WebApi
send
Send the Get request in order to verify the execution cycle as given below. Copy and paste the following Url (http://localhost:57888/api/employees/GetEmp/5) in Postman tool as depicted below in screen shot.
wrap
As soon as you click on the send button it reaches to Custom handler one and goes on to next level. Kindly execute the complete HttpMessegePipeline one by one and add your points.
So far we’ve get into each area of WebApi HttpRequest Pipeline and tried to understand few facts happen during its cycle.
  1. Bullet Points. HttpRequest first converts into HttpRequestMessege.
  2. HttpHandler are type of delegate handler and inject to verify the authenticity and to add some preprocessing logic before it goes further in pipeline. Delegate Handler can be creating on per-route basis. If come error/issue occurs at this level can skip the rest of pipeline.
  3. Authentication filters have been introduced in WebApi2.If come error/issue occurs at this level can skip the rest of pipeline.
  4. Mostly classes are derived from using System.Web.Http.
  5. Model Binders and Value Provides plays an important role in parameter binding as well as the added benefit of FormatterParameterBinding.
  6. WebApi2 gives privilege to return IHttpActionResult from action method of controller. Also supports HttpResponseMessege.
  7. You can manage exception at IHttpAcitonInvoker and at ExceptionFilters also.
  8. This is the final structure of an application given below in screen shot.
    solution
Hope you would read all contexts and liked it.
Download Sample Application : Download Sample App & PPT
Disclaimer
This is all my understanding about WebApi; I’d be happy if you run this sample application and get a chance to share your opinion.

Tuesday, July 5, 2016

Apply Caching In Web API Using CacheCow

Apply Caching In Web API Using CacheCow


In this post, I’ll share about EntityTag caching in Web API. Caching always plays a vital role when we have very frequent requests for model to server, which stores loads of potential information and removes the need to hit server again and again, which helps to enhance Web API performance and reduce the load on server hosting the API. EntityTag is an HttpHeader used for cache conditional requests for resource. EntityTag is also pronounced as ETag.
Let’s take a simple example which use an ETag like “Client sends a request to Http server with Etag value" that holds an updated value for cached resource. The server identifies this with ETag value whether client has an already updated value or it should revert with a latest copy back to client.
ETag's working behavior and implementation
This section elaborates about ETag and its working behavior. Actually ETag is a string representation which is created by server against each request for a resource and also varies as value is updated for resource. For example, 
Initially client sends a request http://localhost:57888/api2/employees/getdetails/5 to server and ask for employeeId 5, as per initial request it won’t be cached and server will return the fresh copy of the requested resource with some ETag value. We’ll see this in illustrations further down in this article. Later client sends the same request to server with header If-None-Matchalong with ETag value which client has received in body response of earlier (e.g. TR6truy7) request If server finds equal ETag value for the requested resource than server responds Http not modified otherwise server will respond with new ETag value.Header “If-None-Match” works only with HttpGet and HttpDelete.
Let’s look in practical implementation. This is the simple structure of an application as given below in image:
solution
Install of CacheCow library: Kindly find the below screen shots to install CacheCow server from NuGet package manager.
NuGet
Click on install button as shown in above screenshot. As soon as you install the CacheCow you will see,
CacheCow.Common.dll and CacheCow.Server dll as depicted in screen below:
CacheCow.Common
Once the installation has done, we need to register CacheCow handler in WebApiConfig.cs file like shown below in depicted image.
execute
  1. //Way to register CacheCowHandler in WebApi.Config file
  2. var objCacheCow = new CacheCow.Server.CachingHandler(config,""); 
  3. config.MessageHandlers.Add(objCacheCow); 
You can read more about how handler works in ASP.NET Web API from here: Global and Per-Route Handler in ASP.NET Web API
The above register CacheCow handler scrutinizes each request and response and verifies the ETag value whether it matches with earlier request or it’s a completely new request. We will see this complete step by step process to understand this here. I’m using fiddler for this purpose.
Step 1: Send the Initial request using fiddler as shown below and press execute,
execute
There is a point of consideration as the response received from server in respect to the request sent by client as shown below in image contains Response Header HTTP 200 OK with the ETag value (a unique representation of each resource).
output
Step 2: We will utilize this ETag value for further communication in order to identify that whether the requested resource exists in the same form or has been changed. If the client sends frequent requesst to server for the same resource than same ETag value will be returned for this request which means no one has updated the value for requested resource.
Note: Kindly send If-None-match parameter in header of request.
header
Output will be like this as shown in given below link:
output
Step 3:
So send the new request using the ETag value received in response of last request as shown in depicted image below. For this purpose, I’ve made slight change in collection that existed in code behind and it should return the updated response value. New ETag value ensures that the requested resource has been changed at server placed in in-memory,
parsed
The above request sends the following output as in the following image:
output
The above image simply states that there is no chanes at server side for this resource. This is how we can manage In-memory caching in Web API and utilize this feature.
feature
Caching plays a vital role where client sends very frequent requess for a resource. CacheCow is one of the good providers to maintain caching in solutions though there are lots of other variants that exist. It is simple in use, easy to install and works very effectively. The one downside which I realized is that you have to keep the updated value of specific ETag sent by server response for each request.
You can download the source code from here : Apply Caching In Web API Using CacheCow