Saturday, March 24, 2018

Call ASP.Net Web API service in a cross domain


In order to call ASP.Net Web API service, add an HTML page in your project. Add reference of JQuery. Your HTML page should look like below.


Two input buttons, one to get list of employees and one to clear the list. An unordered list to show the list of employees.

In the document ready event, write button click events as follows:
Here in this example, both the client and the Web API service are in the same project. So we can use the relative or full path for the controller in ajax call. But if client is in separate project and Web API service is in another project, then it is difficult to call the controller directly using relative or full path.


Calling ASP.Net Web API service in a cross domain using JQuery ajax:
Browsers allow web page to make ajax request only within the same domain. Browser’s security prevents making ajax calls to different domains. This is called same origin policy.

Below urls have same origin.

http://localhost:123/api/Employee
http://localhost:123/Employees.html .


Different origin, because port numbers are different:
http://localhost:123/api/Employees
http://localhost:456/Employees.html


Different origin, because protocols are different:
http://localhost:123/api/Employees
https://localhost:456/Employees.html


Different origin, because domains are different:
http://abc.com
http://abc.net.
For security reasons, browsers do not allow cross domain ajax request. There are two ways to get around with this.
·         JSONP (JSON with Padding)
·         CORS (Cros Origin Resource Sharing)


What is JSONP?
JSONP stands for JSON with Padding. All JSONP does is wraps a data in a function.
In order to allow JSONP to work, we need to install nuget Webcontrib.Formatting.JsonP.  Add below lines of code in WebApiConfig file in Register method


CORS (Cross Origin Resource Sharing):
To enable CORS, we need to install nugget Microsoft.AspNet.WebAPI.Cors package.  Add below lines of code in WebApiConfig file in Register method


FromBody and FromUri attributes in ASP.Net WebAPI

FromBody and FromUri attributes:

Take a look at the Put method we have defined already.
While executing this method from Fiddler, we pass the id parameter from the request uri and the employee parameter from request body.
When a request is issued, the data that we have in a request needs to be mapped to the parameters of the Put method in a controller. We can also pass the id parameter using query string by simply placing a question mark followed by name of the parameter, just like we do in plain ASP.Net.
Now let’s understand what Parameter Binding is. By default ASP .Net web API default parameter binding convention is:
  • If the parameter is of simple type like int, Boolean, double, etc., Web API tries to get the value from uri. (either from route data or querystring).
  • If the parameter is of complex type like Employee, Customer, Product, etc, Web API tries to get the value from the request body.
We can change this default convention by using FromBody and FromUri attributes.
public HttpResponseMessage Put([FromBody]int id, [FromUri]Employee employee)
  • Use [FromBody] attribute to force Web API to get simple types from request body.
  • Use [FromUri] attribute to force Web API to get the complex types from request uri i.e. from route data or querystring.

Look at the below image. We have specified the values for complex type Employee in the request uri.
Note that the name of the parameters should be same as that of the properties defined for the complex type. Here the parameters FirstName, LastName, Gender, Salary are same as that of the properties of the Employee type.
In the below images, we are forcing Web API to look for id parameter in the request body.








Wednesday, March 7, 2018

Custom method names in ASP.Net Web API


By default, the Http verb is mapped to a method in a controller that has the same name as the verb or starts with the verb. E.g. HTTP verb Get is mapped to Get(), GetEmployee() or GetSomething() methods.
If the method does not start with Get or not named Get, then ASP.Net Web API does not know which method in our controller is to be mapped to HTTP verb Get. It is going to fail with an error message “The requested resource does not support http method Get – Status code 405 Method Not Allowed”.
So in order to use custom name for a method we need to decorate the method with HttpGet attribute.

Use query string parameters in Web API:
For our example, we are considering Get method. Depending upon the value we specify for the query string parameter Gender, the Get method should return the data.
FromBody and FromUri:
If parameter is simple type like int, bool, double, etc. then Web API tried to get the values from the URI.
If parameter is of complex type like Customer, Employee, etc, then Web API tries to get the value from request body. This is the default behavior of Web API and called as parameter binding.
To change the default parameter binding process, use FromBody and FromUri attributes.


Use FromBody attribute to force Web API to read simple types from request body and use FromUri attribute to for Web API to read complex types from uri (i.e. from route data or query string).
Pass query string parameters to Web API:

Depending upon the value we provide for the querystring parameter, Get() method should return the data.
If invalid value is provided, then the service should return an error message.


Saturday, February 24, 2018

Content Negotiation in Web API


What is Content Negotiation?

One of the standards of the RESTFul services is that the client should be able to decide the format of the response they want from the server. E.g. does that client want to response in JSON, xml, etc?
When a client sends a request to the server, the request holds accept header. Using this accept header the client can specify the format of the response they want from the server. E.g. if accept header is set to Accept:application/xml, then the server sends the response in xml format. If accept header is set to Accept:application/json, then the response received will be in json format.
When server sends a response in a requested format, it also sets the Content-type header to appropriate value. If the requested format is xml, server sets the Content-type to application/xml and if the requested format is json, it would be set to application/json. So, depending on the value of the accept header in request, the server sends the response. This is called Content Negotiation.
The Web API controller generates the data that we want to send to the client and hand over the data to Web API pipeline which then looks at the accept header and depending on the format specified, Web API will choose the appropriate formatter to format the data. If client has requested xml data, Web API chooses xml formatter and json formatter for json data. These formatters are nothing but classes and these are called MediaTypeFormatter.  We can also create our own custom formatter.
We can also specify multiple formatter in accept header. E.g. if I want both xml and json data, I would specify it as Accept: application/json, application/xml.

We can also specify quality factor in accept header. E.g. Accept: application/json;q=0.4, application/xml;q=0.9. In this case, xml has got higher quality factor than json. So the server sends the data in xml format.
If accept header is not specified, Web API returns the data in json format.
Depending upon the content type specified by the client, the server chooses appropriate formatter. If we set accept header to application/json, the server knows it is dealing with json data and uses appropriate formatter to convert json data to .Net type. These formatters are used by the server for both request and response messages. These formatters are called MediaTypeFormatters.

We can change the settings of these formatters to meet our application’s requirements. Let’s say we want json data to be properly indented or property names should use any particular cases, we can specify it in WebAPICofig.cs file.
Config.formatters.JsonFormatter.SerializerSettings.Formatting = NewtonSoft.Json.Formatting.Indented; 

MediaTypeFormatter is an abstract class from which all the formatters (JsonMediaTypeFromatter, XmlMediaTypeFormatter or custom formatter) are derived from.  

How to return data in a particular format from Web API service?
In WebAPIConfig.cs file’s Register method, add below line of code to return data only in Json format.
config.Formatters.Remove(config.Formatters.XmlFormatter);

This will return the data in only Json format even if accept header is set to application/xml. Similarly if we want the data to be returned in only xml format, we will do
config.Formatters.Remove(config.Formatters.JsonFormatter);

ASP.Net Web API

ASP.Net Web API is a framework which is used to build API (Http Services) on top of the .Net framework. The most common use case for using Web API is for building RESTFul services. These services can then be consumed by broad range of clients like browsers, mobile applications, desktop applications, IOTs. The term IOT stands for Internet of Things. IOTs are the objects or devices that have an IP address and can communicate over the internet with other internet enabled devices and objects. E.g. Security Systems, electronic devices like desktop, laptop, smart phones, etc. Though ASP .Net Web API is widely used to create RESTFul services, it can also be used to create services which are not RESTFul. In short, it does not dictate any architectural style for creating services.


What are RESTFul services?
REST stands for Representational State Transfer, first introduced by Roy Fielding. It is an architectural pattern for creating API that uses Http as its underlined communication mechanism. REST architectural pattern specifies set of constraints that a system should adhere to.

REST constraints: 
1.       Client Server:
Client sends a request, server send a response. This separation of concerns supports the independent evolution of client side logic and server side logic.

2.       Stateless:
The communication between the client and the server should be stateless, which means we should not be storing anything on the server related to the client between requests. The request from the client should contain all the necessary information for the server to process that request. This ensures that each request can be treated independently by the server.

3.       Cacheable:
Sub data provided by the server like list of products, list of department, does not change that often. This constraint tells the client that how long the data is good for, so the client does not have to come back to server over and over again for the same data. Caching avoids unnecessary processing and increased the performance.

4.       Uniform Interface:
It defines an interface between client and a server. To understand uniform interface, we must understand what a resource is and the Http verbs GET, POST, PUT and DELETE. In context of REST APIs, resources typically represent data entities. Product, Employee, Department, etc are all resources. The Http verb GET, PUT, POST, DELETE sent with each request tells the APIs what to do with the resource. Each resource is indentified by a specific Uri.

Let’s look at the below table.  

Resource
Verb
Outcome
/Customers
GET
Gets list of customers
/Customer/1
GET
Gets a customer with id = 1
/Customers
POST
Creates a new customer
/Customer/1
PUT
Updates a customer with id = 1
/Customer/1
DELETE
Deletes a customer with id = 1



Resource here is Customer. So typical Uri would be http://sitename/Customers. This Uri with the verb GET, is going to get us list of Customers.

http://sitename/Customer /1. This Uri with the verb GET would get us a customer with id = 1.
http://sitename/Customers. This Uri with the verb POST would create a new customer.
And you are smart enough to understand the functions of remaining verbs.

Another concept related to Uniform Interface is HATEOS (Hypermedia as the Engine of Application State). It means that in each request, there will be a set of hyperlinks that lets you know what other actions can be performed on the resource.


When to choose WCF services?
We can also use WCF service to convert into a RESTFul service but it requires a lot of configuration. The more natural choice to create a RESTFul service would be a Web API which is specifically created to create a RESTFul service. 
a.       WCF is used when you want to create a service which is transport/protocol independent. A single service with multiple endpoints. Suppose you have two clients, a java client and a .Net client. Java client wants message in XML format over Http protocol and .Net client wants binary message over tcp protocol. We can simply define two endpoints for two clients and our work is done.

b.      If you have an existing SOAP service but want to add REST to reach more clients, use WCF service.

c.       If you have limitation of using .Net framework 3.5, use WCF service.