Wednesday, July 16, 2014

Web API Notes

Whats WEBAPI ?

  • 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. 
  • With WebAPI content negotiation, we can return data based on the client requests,  if the client is requesting the data to be returned as JSON or XML, the WebAPI framework deals with the request type and returns the data appropriately based on the media type. By default WebAPI provides JSON and XML based responses.
  • The client can make a GET, PUT, POST, and DELETE request and get the WebAPI response appropriately.
Content Negotiation in WebAPI

  • Content negotiation is the process of selecting the best representation for a given response when there are multiple representations available. The underling Web API framework implements the content negotiation and that is the reason why and how the client can request data with a specific media type.
  • By default the Web API returns data in JSON forMat, however while requesting for a resource we can specify the media type to return so that the WebAPI knows what you are requesting for and select the proper formatter to output the data. 
How to implement WebAPI

  • Create WebApiConfig.cs wherein we defines routes in the route tabl.e

routes.MapHttpRoute(
    name: "API Default",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
  • Create a Class which derives from ApiController
  • Define the GET/PUT/POST/DELETE methods defined in the WebAPI controller map to the HTTP methods. 
Routing 

public class ProductsController : ApiController

{
    [AcceptVerbs("GET", "HEAD")]
    public Product FindProduct(id) { }

    // WebDAV method
    [AcceptVerbs("MKCOL")]
    public void MakeCollection() { }
}

WebAPI Hosting Options
WebAPI can be hosted on IIS/Self Hosted.

Parameter Binding in WebAPI

There are various rules for binding the parameters:
  • "Simple" type: If the parameter is the simple type then it is a string convertible parameter that includes the preemptive data types such as Int, Double, Bool and so on with the Date Time, Decimal, string and so on. By default these are read from the URI.
  • "Complex" type: If the parameter is a complex type then the Web API catches the value from the message body. It uses the media type formatters for catching the value from the body.
FromURI Binding : 

In the From URI binding we use the [FromUri] attribute. The [FromUri] attribute is inherited from the [ModelBinder] attribute. Let's see an example:
GET/products?pageNo=1&price=20&size=xxl

public class Product
    {
        public int pageNo { get; set; }
        public decimal Price { get; set; }
        public int size { get; set; }
    }

FromBody Binding
public HttpResponseMessage Post([FromBodystring Address)

Self Host

Uri myUri = new Uri(@"http://localhost:9999");
// Let have our configurations readY
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(myUri); 

HttpSelfHostServer server = new HttpSelfHostServer(config);

// Start listening 
server.OpenAsync().Wait();

// Wait for it :)
Console.WriteLine("WebApi hosted on " + myUri.AbsoluteUri +" It can be tested now");
Console.ReadLine();

WebAPI / JQuery Integration
Assuming the Web API is hosted on IIS at http://localhost:8080/API_SVC/api/EmployeeAPI
--Get Operation

function GetAllEmployees() {
        jQuery.support.cors = true;
        $.ajax({
            url: 'http://localhost:8080/API_SVC/api/EmployeeAPI',
            type: 'GET',
            dataType: 'json',            
            success: function (data) {                
                WriteResponse(data);
            },
            error: function (x, y, z) {
                alert(x + '\n' + y + '\n' + z);
            }
        });        
    }
--Post Operation

function AddEmployee() {
        jQuery.support.cors = true;
        var employee = {
            ID: $('#txtaddEmpid').val(),
            EmpName: $('#txtaddEmpName').val(),
            EmpDepartment: $('#txtaddEmpDep').val(),
            EmpMobile: $('#txtaddEmpMob').val()
        };       
        
        $.ajax({
            url: 'http://localhost:8080/API_SVC/api/EmployeeAPI',
            type: 'POST',
            data:JSON.stringify(employee),            
            contentType: "application/json;charset=utf-8",
            success: function (data) {
                WriteResponse(data);
            },
            error: function (x, y, z) {
                alert(x + '\n' + y + '\n' + z);
            }
        });
    }

WebAPI Security

1) Enable Windows Authentication
  • web.config

<system.web>
    <authentication mode="Windows" />
</system.web>

2) Enable CORS Support
  • Browser security prevents a web page from making AJAX requests to another domain. This restriction is called thesame-origin policy
  • Cross Origin Resource Sharing (CORS) is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others.
  • Enable CORS in WebAPI
    • Import Package Microsoft,AspNet.webApi.Cors
    • in the WebApiConfig . register enable CORS 
public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

    • Next Enable the CORS Attribute in the Controller;s

[EnableCors(origins: "http://myclient.azurewebsites.net", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...

    }

No comments:

Post a Comment