Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Web API's MVC

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 671
    Comment on it

    Web API's

    Asp.net web Api's is a framework to build http services for web servers and browsers. It gathers definitions, procedures and protocols to help the communication between different computer softwares. HTTP services for example, is built by ASP.NET Web API in order to reach a variety of clients such as iphones, mobiles. It also supports to build RestFul Applications on .net framework

    Web API Features

    1. It supports convention-based CRUD Actions since it works with HTTP verbs GET,POST,PUT and DELETE.
    2. Responses have an Accept header and HTTP status code.
    3. Responses are formatted by Web APIs MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.
    4. It may accepts and generates the content which may not be object oriented like images, PDF files etc.
    5. It has automatic support for OData. Hence by placing the new [Queryable] attribute on a controller method that returns IQueryable, clients can use the method for OData query composition.
    6. It can be hosted with in the application or on IIS.
    7. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection that makes it more simple and robust.

    To whom choose between WCF Vs WEB API

    1. WCF must be used if the services is made for one way messaging, message queues, duplex communication etc.

    2. WCF can use fast transport channels available, such as TCP, Named Pipes,or maybe even UDP (in WCF 4.5),support HTTP when all other transport channels are unavailable.

    3. API's are used when a resource oriented services are made over http(like URIs, request/response headers, caching, versioning, various content formats).

    4. API's can be used when we want to expose our service to a broad range of clients ncluding browsers, mobiles, iphone and tablets.

    Differences between Web API and Web Services

    1. All Web services are APIs but all APIs are not Web services.

    2. A web service typically offers a WSDL from which you can create client stubs automatically. Web Services are based on the SOAP protocol, whereas web API is a newer Microsoft framework which helps you to build REST based interfaces. The response can be either JSON or XML, but there is no way to generate clients automatically because Web Api does not offer a service description like the WSDL from Web Services.

    Sample of Web APIs

    namespace Employee.Controllers
     {
      public class EmployeeController : ApiController
       {
          private static EmployeeRepository _employeeRepository = new EmployeeRepository();
          public List<Employees> Get()
           {
             List<Employees> lstEmployee = new List<Employees>();
             lstEmployee = _employeeRepository.getAllEmployee();
             return lstEmployee;
           }
    
          public Employees Get(int id)
           {
             Employees empObj = new Employees();
             empObj = _employeeRepository.getEmployeeById(id);
             return empObj;
           }
    
          public HttpResponseMessage Post([FromBody] Employees emp)
           {
             var response = new HttpResponseMessage();
             Employees empobj = _employeeRepository.InsertEmployee(emp);
             if (empobj == null)
                {
                  response=Request.CreateErrorResponse(HttpStatusCode.NotFound,"no records found");
                }
              else
                {
                  response = Request.CreateResponse(HttpStatusCode.OK);
                }
             return response;
           }
    
    
          public HttpResponseMessage Put([FromBody] Employees emp)
           {
             var response = new HttpResponseMessage();
             bool value = _employeeRepository.UpdateEmployee(emp);
             if (value != true)
                {
                  response=Request.CreateErrorResponse(HttpStatusCode.NotFound,"no records found");
                }
              else
                {
                  response = Request.CreateResponse(HttpStatusCode.OK);
                }
             return response;
           }
    
          public HttpResponseMessage Delete(int id)
           {
             var response = new HttpResponseMessage();
             bool value = _employeeRepository.DeleteEmployee(id);
             if (value == false)
                {
                  response=Request.CreateErrorResponse(HttpStatusCode.NotFound," no record found");
                }
              else
                {
                  response = Request.CreateResponse(HttpStatusCode.OK);
                }
             return response;
           }
        }
    }
    

    As we can use only four kind of methods like get(),put(),post(),delete().So to make use of first method
    public IEnumerable Get() we will write url as: http://localhost:7167/api/employee/
    Similarly for the second method
    public string Get(int id) we will write url as: http://localhost:7167/api/employee/5


    For the operations of POST, PUT and DELETE Fidler (software) must be used.

    The request will be sent to thr repository from controller for further processing

    Repository

    namespace Employee.Repository
    {
     public class EmployeeRepository
     {
        private HttpRequestMessage request;
        public EmployeeRepository()
         {
            request = new HttpRequestMessage();
            request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());
         }
        private static List<Employees> employee = new List<Employees>()
         {
            new Employees{ EmployeeId =1032, Name ="Imran",Designation = "Ghani",Age=24, address=""},
            new Employees{ EmployeeId =1022, Name ="Salma",Designation = "Ahmad",Age=28, address=""},
            new Employees{ EmployeeId =1092, Name ="Reha",Designation = "Ahmad" ,Age=33, address=""},
            new Employees{ EmployeeId =1044, Name ="Zees",Designation = "Khalid",Age=38, address=""}
         };
    
        public List<Employees> getAllEmployee()
         {
              return employee;
         }
        public Employees getEmployeeById(int Id)
         {
             var employees = employee.FirstOrDefault((emp) => emp.EmployeeId == Id);
             if (employees == null)
              {
                 throw new HttpResponseException(HttpStatusCode.NotFound);
              }
             return employees;
         }
    
        public Employees InsertEmployee(Employees insertemp)
         {
              employee.Add(insertemp);
              return insertemp;
         }
    
         public bool UpdateEmployee(Employees emp)
         {
              int empId = emp.EmployeeId;
              Employees existEmployees = getEmployeeById(empId);
              if (existEmployees != null)
              {
                 existEmployees.Name = emp.Name;
                 existEmployees.Designation = emp.Designation;
                 existEmployees.address = emp.address;
                 return true;
              }
            else
              {
                 return false;
              }
         }
    
        public bool DeleteEmployee(int Id)
         {
             Employees delemployee = getEmployeeById(Id);
             if (delemployee != null)
              {
                 employee.Remove(delemployee);
                 return true;
              }
            else
                return false;
         }
    
     }
    }
    

    Commonly used HTTP Status codes

    200
    OK : Its a response for successful HTTP requests.In a GET request, the response will contain an entity corresponding to the requested resource. In a POST request the response will contain an entity describing or containing the result of the action.

    204
    No Content: Request Sucessfully processed, but is not returning any content. Usually used as a response to a successful delete request.

    400
    Bad Request: The server cannot or will not process the request due to something that is perceived to be a client error.

    404
    Not Found: The Requested resource is not found but might be available in future. Subsequent requests by the client are permissible.

    408
    Request Timeout: Server time out waiting for the request from the user.According to HTTP specifications: "The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.

    500
    Internal Server Error: A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.

    505
    HTTP Version Not Supported: Server doesn't support the http protocol used in request.

    Refrences:

    http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

    http://www.dotnet-tricks.com/Tutorial/webapi/VG9K040413-What-is-Web-API-and-why-to-use-it-?.html

    http://www.codeproject.com/Articles/549152/Introduction-to-ASP-NET-Web-API

    http://en.wikipedia.org/wiki/Web_API

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: