how to create web api in asp.pdf

11
Ask a Question READER LEVEL: ARTICLE This article explains what the Web API is and its basics. How to Create Web API in ASP.Net MVC By Saineshwar Bageri on Nov 24, 2014 Download Files: WebAPIBasic.rar This article explains what the Web API is and its basics. The preceding image is from: http://forums.asp.net/t/1903769.aspx?When+to+use+web+api Let's start with a definition first. Web API The 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. The ASP.NET Web API is an ideal platform for building Restful applications on the .NET Framework. Referred from “Microsoft.com”. Why to use the Web API Currently most mobile devices, browsers and tablets are the medium for accessing most of the internet and in this also people are using mobile apps the most and to provide data to apps we are now going to use the Microsoft new technology called Web API. When to use it If you want to expose the data/information of your application to your clients and other people then that other people can use your data and interact with the data/information you expose to them. For example, a mobile application requires a service. HTML 5 requires a service. Desktop PC and tablets require services. Currently most device apps require Web API services. The ASP.Net Framework leverages both web standards such as HTTP, JSON and XML and it provides a 01 Basics of AngularJS: Part 1 02 Google+ Authentication in ASP.Net 03 How to Configure SharePoint Server in Windows Azure 04 How to Create Nodejs Module and Publish Over to Npm 05 AngularJS Shopping Cart Using MVC and WCF Rest Service 06 Learn Simple MVVM and Command Bindings in 15 Mins 07 Basics of AngularJS: Part 2 08 jQuery Validation Plugin to Validate Web Forms 09 Simplify JavaScript Object Oriented Programming Model: Part 1 10 ASP.Net SignalR: Building a Simple Real-Time Chat Application View All TRENDING UP Follow @csharpcorner In Focus MUST READ: Authors How to improve your Writing Skills Contribute Basics of AngularJS: Part 1 C# Corner Search 44.0 k 15 6 TECHNOLOGIES ANSWERS BLOGS VIDEOS INTERVIEWS BOOKS NEWS CHAPTERS CAREER ADVICE JOBS

Upload: prasanth-jayaprakash

Post on 18-Sep-2015

43 views

Category:

Documents


0 download

TRANSCRIPT

  • Ask a Question

    READER LEVEL:ARTICLE

    This article explains what the Web API is and its basics.

    How to Create Web API in ASP.Net MVCBy Saineshwar Bageri on Nov 24, 2014

    Download Files: WebAPIBasic.rar

    This article explains what the Web API is and its basics.

    The preceding image is from: http://forums.asp.net/t/1903769.aspx?When+to+use+web+api

    Let's start with a definition first.

    Web API

    The ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range ofclients, including browsers and mobile devices.

    The ASP.NET Web API is an ideal platform for building Restful applications on the .NET Framework. Referredfrom Microsoft.com.

    Why to use the Web API

    Currently most mobile devices, browsersand tablets are the medium for accessing most of the internet andin this also people are using mobile apps the most and to provide data to apps we are now going to use theMicrosoft new technology called Web API.

    When to use it

    If you want to expose the data/information of your application to your clients and other people then thatother people can use your data and interact with the data/information you expose to them.

    For example, a mobile application requires a service.

    HTML 5 requires a service.

    Desktop PC and tablets require services.

    Currently most device apps require Web API services.

    The ASP.Net Framework leverages both web standards such as HTTP, JSON and XML and it provides a

    01 Basics of AngularJS: Part 1

    02 Google+ Authentication in ASP.Net

    03 How to Configure SharePoint Server inWindows Azure04 How to Create Nodejs Module andPublish Over to Npm05 AngularJS Shopping Cart Using MVCand WCF Rest Service06 Learn Simple MVVM and CommandBindings in 15 Mins07 Basics of AngularJS: Part 2

    08 jQuery Validation Plugin to ValidateWeb Forms09 Simplify JavaScript Object OrientedProgramming Model: Part 110 ASP.Net SignalR: Building a SimpleReal-Time Chat Application

    View All

    TRENDING UP

    Follow@csharpcorner

    In Focus MUST READ: Authors How to improve your Writing Skills

    Contribute

    Basics of AngularJS: Part 1 C#CornerSearch

    44.0 k 15 6

    TECHNOLOGIES ANSWERS BLOGS VIDEOS INTERVIEWS BOOKS NEWS CHAPTERS CAREER ADVICE JOBS

  • simple way to build and expose REST based data services.

    Some core concepts of ASP.Net MVC are similar to the ASP.Net Web API such as routing and controllers.

    Requirements

    We are using Visual Studio 2012 for a demo application.

    Building a Web API

    Let's start with creating a Web API project.

    Start Visual Studio and select New project from the Start page or from the File menu select "File" > "New" > "Project...".

    In the template pane select Installed Templates and expand the Visual C# menu. Inside that Visual C# selectWeb. In the list of projects select ASP.Net MVC 4 Web Application.

    And name the project WebAPI_Basic.

    For reference see the following snapshot.

    After adding, a new dialog will popup.

    Inside the project template select Web API and in the view engine select Razor.

    A new project is created now.

    Let's begin with adding Web API Controller

  • Now let's begin with adding a Web API Controller. It is nearly similar to adding a Controller in ASP.NET MVC.

    Rightclick on the Controller folder and add a new Web API Controller with the name CarDetailsControllerand in the template select API Controller with an empty read / write action.

    After adding the Controller you will see the code as in the following snapshot.

    You can keep this Web API controller anywhere in the application.

    If you want to follow the convention then create the new folder in the root your of application with thename API.

    Inside that you can add a Web API controller.

    You have successfully added a Web API controller to your application.

    Now you can run the application and test it.

    For testing I am passing http://localhost:32359/api/cardetails/1 for calling the method get.

    Wow, it's working!

  • It's easy to configure it as aWeb API.

    The ASP.Net MVC and ASP.Net Web API makes heavy use of convention for configuration to lighten thework load for creating the services.

    For example, add a decorating method with attributes to make it easy to do CRUD operations.

    Else it will make it difficult to understand and code.

    01. [HttpPut]02. publicvoidPut(intid,[FromBody]stringvalue)03. {04. 05. }06. [HttpPost]07. publicvoidPost([FromBody]stringvalue)08. {09. 10. }11. [HttpDelete]12. publicvoidDelete(intid)13. {

    The HTTP actions and their corresponding CRUD operations are:

    GET Read

    Retrieves the representation of the resource.

    PUTUpdate

    Update an existing resource.

    POST Create

    Create new resource.

    DELETE Delete

    Delete an existing resource.

    Now let's begin with how to create a CRUD operation with the WEB API.

    Let's start by adding a Model.

    To add the model rightclick on the model folder and add a class with the name CarsStock.

  • After adding the Model CarsStock.cs now let's start with adding properties to the class.

    After adding the model properties now I will consume the HTTP service developed using the ASP.NET WebAPI in a simple cshtml page with jQuery and Ajax.

    For that in the View folder I will add a folder named Car and inside that folder will add a CarStock namedview. To add it just rightclick on the View folder and select View.

    The following snapshot shows how I had added the view.

    After adding the view you will get a blank view because we are not using any tightly coupled model here.

    Then add a Controller with the name CarController. Call this view Carstock for the demo of consuming theWeb API.

    In this I called the view CarStock.

  • After adding the Controller and View now let us move back towards the Web API and make some changesthat we have already created with the name CarDetailsController.

    Let's get to the first method in CarDetailsController.

    1. GET IEnumerable

    01. [HttpGet]02. publicIEnumerableGetAllcarDetails()03. {04. CarsStockST=newCarsStock();05. CarsStockST1=newCarsStock();06. Listli=newList();07. 08. ST.CarName="MarutiWaganor";09. ST.CarPrice="4Lakh";10. ST.CarModel="VXI";11. ST.CarColor="Brown";12. 13. ST1.CarName="MarutiSwift";14. ST1.CarPrice="5Lakh";15. ST1.CarModel="VXI";16. ST1.CarColor="RED";17. 18. li.Add(ST);19. li.Add(ST1);20. returnli;21. }

    This method is used to get a list of data.

    In this method I have used the Model CarsStock and created a list of CarsStock List.

    And returning it.

    2. GET by id

    01. publicIEnumerableGet(intid)02. {03. CarsStockST=newCarsStock();04. CarsStockST1=newCarsStock();05. Listli=newList();06. if(id==1)07. {08. ST.CarName="MarutiWaganor";09. ST.CarPrice="4Lakh";10. ST.CarModel="VXI";11. ST.CarColor="Brown";12. li.Add(ST);13. }14. else15. {16. ST1.CarName="MarutiSwift";17. ST1.CarPrice="5Lakh";18. ST1.CarModel="VXI";19. ST1.CarColor="RED";20. li.Add(ST1);21. }22. returnli;23. }

    In this GET method you can retrieve records for the database by passing an id.

    3. POST

    01. [HttpPost]02. publicvoidPostCar([FromBody]CarsStockcs)03. {04. 05. }

  • In this POST method you can post data CREATE to the database. In this I am using the Carstockmodel to post the data.

    4. PUT

    01. [HttpPut]02. publicvoidPutcar(intid,[FromBody]CarsStockcs)03. {04. 05. }

    In this PUT method you can UPDATE the data UPDATE to the database. I am using the Carstockmodel to update the data.

    5. DELETE

    01. [HttpDelete]02. publicvoidDeletecar(intid)03. {04. 05. }

    In this DELETE method you can delete data DELETE from the database. I am using an id to delete the data.

    Here is a snapshot of all the methods and models after adding the attributes to it.

    Now let's move to the view and do CRUD operations from there.

    For getting a list of data I have created a function in jQuery.

    1. Calling GET IEnumerable List from Ajax and getting data from the Web API.

    01. 02. 03. functionAllcarDetails(){04. $.ajax({05. type:"GET",06. url:"http://localhost:32359/api/Cardetails",//URI07. 08. dataType:"json",09. success:function(data){10. debugger;11. vardatadatavalue=data;12. varmyJsonObject=datavalue;13. contentType:"application/json";14. $.each(myJsonObject,function(i,mobj){15. $("#Cartbl").append('

    '+mobj.CarName+16. ''+mobj.CarModel+17. ''+mobj.CarPrice+18. ''+''19. +mobj.CarColor+'');20. 21. });22. 23. },24. error:function(xhr){25. alert(xhr.responseText);26. }27. });28. 29. }

  • 2. Calling PostCar Method using Ajax and posting data to the Web API.

    01. functionPostData()02. {03. 04. varcardetails=05. {06. CarName:"Ertiga",07. CarModel:"LXI",08. CarPrice:"5000000",09. CarColor:"blue"10. };11. 12. $.ajax({13. type:"POST",14. data:JSON.stringify(cardetails),15. url:"http://localhost:32359/api/Cardetails",16. dataType:"json",17. contentType:"application/json",18. });19. 20. }

    3. Calling the PUTcar method using Ajax and updating the data of the Web API.

    01. functionPutData(){02. 03. varcardetails=04. {05. 06. CarName:"Ertiga",07. CarModel:"LXI",08. CarPrice:"5000000",09. CarColor:"blue"10. 11. };12. 13. vart=JSON.stringify(cardetails);14. varid="0";15. $.ajax({16. url:'http://localhost:32359/api/Cardetails/'+id,17. type:"put",18. contentType:"application/json;charset=utf8",19. data:t,20. dataType:"json",21. 22. });23. }

    4. Calling the Delete car method using Ajax and to delete data of the Web API.

    01. functiondeleteData1()02. {03. varid=0;04. $.ajax({05. url:'http://localhost:32359/api/CarDetails/'+id,06. type:'DELETE',07. success:function(data){08. 09. },10. error:function(data){11. alert('Problemindeletingcar:'+data.responseText);12. }13. });14. }

    5. Calling GET by ID from Ajax and getting data from the Web API by id.

    01. functionGetCarById(){02. varid=1;03. $.ajax({04. url:'http://localhost:32359/api/CarDetails/'+id,05. type:'GET',06. dataType:"json",07. success:function(data){08. 09. vardatavalue=data;10. varmyJsonObject=datavalue;11. 12. varCarModel=myJsonObject[0].CarModel;13. varCarName=myJsonObject[0].CarName;14. varCarColor=myJsonObject[0].CarColor;15. varCarPrice=myJsonObject[0].CarPrice;16. 17. $(''+CarModel+''+CarName+18. ''+CarColor+''+'

    '+CarPrice+'').appendTo('#Cartbl');19. },20. error:function(xhr){21. alert(xhr.responseText);22. }23. });24. }

    After completing all the functions of Ajax I am now displaying the view CarStock.

  • In the carstock view I have just added 5 buttons and on the click event of every button a different functionof the Web API is called.

    The following snippet is debugged in Firebug.

    Final Output

    Here in this view I have consumed a Web API for Demo.

    I know that now all my web developer friends must have a basic understanding of what the Web API is.

    Saineshwar BageriI am Software Developer and MVP from c-sharpcorner working on .Net Web Technology (Asp.net , C# , Sqlserver , MVC , Windows ,Console Application, javascript , jquery , json ,ORM Dapper) and also freelance ... Read more

  • RELATED ARTICLES

    Personal Blog:http://dotnet-sai.blogspot.in

    Rank112

    1.3mReaders

    BronzeMember

    1Time

    Implement ASP.Net Web API 2 in ASP.Net MVC5

    Difference Between MVC and Web APIIntroduction To New Release Candidates ForMVC 5.1 and Web API 2.1

    ASP.Net MVC 5 Web API Consuming at ClientSide

    How ASP.Net Web API WorksDisplay Data in ASP.NET Web API MVC 4 View

    Create Read Operation in Web API Using MVC 4 Introducing ASP.Net Web API 2: Day 1Introducing ASP.Net Web API 2- AddingController: Day 2

    Create and Consume Web API in MVC 4

    COMMENTS 15of10View Previous Comments >>

    Nov 24, 2014

    5 12.8k 4.2m 2 0 Post Reply

    Great work Saineshwar.Dinesh Beniwal

    Nov 25, 2014

    626 1 0 1 0 Post Reply

    Nice sai...Pranit Dange

    Nov 25, 2014

    621 6 0 1 0 Post Reply

    Congratz..Nice ArticlePrashant Pande

    Nov 27, 2014

    142 1.2k 295.2k 1 0 Post Reply

    Saineshwar Bageri sir can you explain how to consume services without ajax calls, might be imean to ask , call PUT,POST,DELETE services in MVC controller.Rajeev Ranjan

    Dec 02, 2014

    239 633 232.4k 0 0 Post Reply

    Nicely explained about Web API.Pradip Pandey

    Dec 11, 2014

    625 2 0 1 0 Post Reply

    Nice Article...Anjani Pandey

    Dec 18, 2014

    470 158 0 0 0 Post Reply

    Great work...Humayun Kabir Mamun

    Jan 14, 2015

    5 12.8k 4.2m 1 0 Post Reply

    Congratulations Sai, one more articles of the day on ASP.NETDinesh Beniwal

    Jan 14, 2015

    112 1.5k 1.3m 0 0 Post Reply

    thanks Dinesh Beniwal sir once again on Asp.netSaineshwar Bageri

    Jan 14, 2015

    625 2 0 0 0 Post Reply

    Great ...... Congrates :)Anjani Pandey

    Type your comment here and press Enter Key....

    COMMENT USING

  • Hosted By CBeyond Cloud Services

    2015 C# Corner. All contents are copyright of their authors.

    MVPs MOST VIEWED LEGENDS NOW PRIZES REVIEWS SURVEY CERTIFICATIONS DOWNLOADS

    CONTACT US PRIVACY POLICY TERMS & CONDITIONS SITEMAP REPORT ABUSE

    PHOTOS CODE SNIPPETS CONSULTING TRAINING STUDENTS MEMBERS MEDIA KIT ABOUT US LINKS IDEAS