asp.net web api 2: beginner guide -...

44

Upload: others

Post on 05-Jan-2020

26 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET
Page 2: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

ContentsIntroduction

ImplementingaWebAPIProject

PassingComplexObjectstoaWebAPIMethod

WebAPIClientImplementations

WorkingwiththeHttpClientAPI

AccessingtheWebAPIfromjQuery

PassingaParameterfromjQuery

ScaffoldingwithWebAPI

ScaffoldontheEntityFramework

RoutinginASP.NETWebAPI

AttributeRouting

ImplementingMultipleSerializationMethods

UsingJSONSerialization

UsingXMLSerialization

HelpPageGenerationfromXMLDocumentation

WCFviaWebAPI

References

Page 3: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET
Page 4: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

AbouttheauthorAmbilyhavebeenaMicrosoftMVPin2011andaMicrosoftTechnologyEvangelist.Herfocus area includes .NET technologies, Windows 8, Team Foundation Server andHTML5/jQuery.SheisalsoanauthorforSimple-Talk,CodeProjectanddotnetfunda.Herblogisathttp://ambilykk.com.

Page 5: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET
Page 6: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

Aboutthisbook

ThisshortBookexplainsWebAPIdesign,concepts,features,andhelppagegeneration.This isastarterguidefor thosewhowant toquicklyunderstandthebasicsofWebAPI.Topicscoveredinthisbookare:

ImplementingWebAPIWebAPIClientImplementations–ASP.NETMVCandjQueryScaffoldingwithWebAPI–EntityFrameworkRoutinginWebAPIImplementingMultipleSerializationOptionsHelpPageGeneration

Share your feedbacks, criticisms, and suggestions of improvements [email protected]

Page 7: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET
Page 8: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

IntroductionASP.NETWebAPIisaframeworkforbuildingHTTPservicesthatcanbeaccessedfromvariousclients,suchasbrowsersandmobiledevices.ASP.NETWebAPIwasintroducedaspartofASP.NETMVC4;however,ithasitsoriginsinWCFasWCFWebAPI.Thisnew HTTP service model is simple to develop and contains common HTTP features,includingCaching,StatusCode,andsoon.

Inthisshortbook,wewilldiscussWebAPIdesign,concepts,features,andcompareWebAPIwithWCF.

Page 9: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

ImplementingaWebAPIProjectLet’sstartourdiscussionwithasampleWebAPIproject.WewillbeusingVisualStudio2013asourdevelopmentenvironment.OurfirststepwillbetocreateanASP.NETMVCprojectbasedontheWebAPItemplate,asshowninFigure1.

Figure1:CreatinganASP.NETMVCprojectbasedontheWebAPItemplate

Next,we’ll create a samplemodel inside themodel folder in theMVC solution.RightclickontheModelfolderfromthesolutionexplorerandselectAdd->ClassasshowninFigure2.

Figure2:AddnewModel

Forthiswalk-through,IamusingtheProductmodeldefinedinListing1.

Listing1:DefiningtheProductmodel

Page 10: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

publicclassProduct

{

publicintId{get;set;}

publicstringName{get;set;}

publicstringCategory{get;set;}

publicdecimalPrice{get;set;}

}

Oncetheproductmodelisready,letuscreateanewAPIcontrollerinsidethecontrollers’folder toprocess theProductmodel.Bydefault, anMVCprojectbasedon theWebAPItemplate adds two controllers: one inherited from theController class and the other fromApiControllerclass.

Right-click the controllers folder in Solution Explorer and add a new controller byselectingtheEmptyAPIcontrolleroptionundertemplateasshowninFigure3.

Figure3:AddEmptyAPIController

Provideappropriatenameforthenewcontroller;sayProductsController.

Figure4:AddController

ProductsController will define two methods for getting list of products and selected

Page 11: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

product based on product id. The code for the sample controller should look like thatshowninListing2.

Listing2:AddinganApiControllerclasstothesampleproject

publicclassProductsController:ApiController

{

//Definetheproductslist

List<Product>products=newList<Product>();

///<summary>

///WebAPImethodtoreturnlistofproducts

///</summary>

///<returns></returns>

publicIEnumerable<Product>GetAllProducts()

{

GetProducts();

returnproducts;

}

privatevoidGetProducts()

{

products.Add(newProduct{Id=1,Name=“Television”,Category=“Electronic”,Price=82000});

products.Add(newProduct{Id=2,Name=“Refrigerator”,Category=“Electronic”,Price=23000});

products.Add(newProduct{Id=3,Name=“Mobiles”,Category=“Electronic”,Price=20000});

products.Add(newProduct{Id=4,Name=“Laptops”,Category=“Electronic”,Price=45000});

products.Add(newProduct{Id=5,Name=“iPads”,Category=“Electronic”,Price=67000});

products.Add(newProduct{Id=6,Name=“Toys”,Category=“GiftItems”,Price=15000});

}

///<summary>

///WebAPImethodtoretrurnselectedproductbasedonthepassedid

///</summary>

///<paramname=“selectedId”></param>

///<returns></returns>

publicIEnumerable<Product>GetProducts(intselectedId)

{

if(products.Count()>0)

{

Page 12: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

returnproducts.Where(p=>p.Id==selectedId);

}

else

{

GetProducts();

returnproducts.Where(p=>p.Id==selectedId);

}

}

}

RuntheprojectandaccesstheAPIbyappendingtheuniformresourcelocator(URL)with/api/Products,asinhttp://localhost:59509/api/Products.ThisapicallwillreturnthelistofProducts.WecanalsoaccesstheGetProductsmethodbypassingtheSelectedIdargumentaspartofthequerystring:http://localhost:59509/api/Products?SelectedId=2.

By defaultWeb API returns JSON data, so when you run theWeb API directly frombrowser,itwillprompttosaveoropentheJSONoutput.FollowingFigureshowstheapioutputforthe/api/Productsrequest.

Figure5:WebAPIResponse-JSONformat

Page 13: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

PassingComplexObjectstoaWebAPIMethodPassingasimplevalueisastraightforwardprocessinWebAPI,butinmostcasesyou’llneedtopassacomplexobjectasamethodparameter.Youcanpasstheseobjectseitherbyusingthe[FromUrl]orbyusing[FromBody]attribute.The[FromBody]attributereadsdatafromtherequestbody.However, theattributecanbeusedonlyoncein themethodparameterlist.

LetusunderstandtheimportanceofusingcomplexparametersusingthecodesnippetinListing3,whichexpectsacomplexobject,Time,asitsinput.

Listing3:Passingacomplexobjectasamethodparameter

publicclassSampleController:ApiController

{

///<summary>

///Getthetimebasedonpassedparameters

///</summary>

///<paramname=“t”></param>

///<returns></returns>

publicstringGetTime(Timet)

{

returnstring.Format(“ReceivedTime:{0}:{1}.{2}”,t.Hour,t.Minute,t.Second);

}

}

publicclassTime

{

publicintHour{get;set;}

publicintMinute{get;set;}

publicintSecond{get;set;}

}

Now,letustrytopassthevaluestotheGetTimemethodusingtheHour,MinuteandSecondvalues.ThiswillthrowtheObjectreferencenotsettoaninstanceofanobjectexception.

Eventhoughwehavementionedthevaluesrelatedtothefieldsof theTimeobject,APImethodisnotabletomapthevaluesproperlytotheparameter.Nowmodifythecodetoinclude the [FromUri] attribute so it canhandle thecomplexobject fromquerystring.Asyoucanseeinthefollowingsnippet,weincludethe [FromUri]attributebeforespecifyingtheTimeobject:

publicstringGetTime([FromUri]Timet)

Page 14: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

{––––––-}

InvokethewebAPImethodwiththesamevaluesbeforeandobservetheresult,asshowninFigure5.

Figure6:ReceivingsuccessfulresultswhencallingtheGetTimemethod

Page 15: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET
Page 16: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

WebAPIClientImplementationsWebAPIcanbeconsumedfromdifferentapplicationsincludingwebapplications,clientsidetechnologieslikejQueryandAngularJS,nativemobileapplicationsandsoon.Thissection discuss about how we can invoke Web API from various client applications;ASP.NETMVCandjQuery.

Page 17: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

WorkingwiththeHttpClientAPIHttpClient is an extensible API for accessing any services or web sites exposed overHTTP. The HttpClient API was introduced as part of the WCFWeb API but is nowavailableaspartofASP.NETWebAPIin.NETFramework4.5.YoucanuseHttpClienttoaccessWebAPImethodsfromacode-behindfileandfromservicessuchasWCF.

The code snippet shown in Listing 4 creates an HttpClient object and uses it forasynchronousaccesstoproductsAPImethods.Referthecodecommentstounderstandthecodesnippet.

Listing4:CreatinganHttpClientobjecttoaccesssampleAPImethods

//asynchronousaccessingofwebapimethod

asyncTaskGetData()

{

StringBuilderresult=newStringBuilder();

//DefinethehttpClientobject

using(HttpClientclient=newHttpClient())

{

//DefinethebaseaddressoftheMVCapplicationhostingthewebapi

//accessingthewebapifromthesamesolution

client.BaseAddress=newUri(HttpContext.Current.Request.Url.AbsoluteUri);

//Definetheserializationusedjson/xml/etc

client.DefaultRequestHeaders.Accept.Add(

newMediaTypeWithQualityHeaderValue(“application/json”));

//Callthemethod

HttpResponseMessageresponse=client.GetAsync(“api/products”).Result;

if(response.IsSuccessStatusCode)

{

//Converttheresultintobusinessobject

varproducts=response.Content.ReadAsAsync<IEnumerable<Product>>().Result;

foreach(varpinproducts)

{

result.Append(string.Format(“{0}–[Price:{1}Category:{2}]”,p.Name,p.Price,p.Category));

}

}

else

{

result.Append(string.Format(“Error Code:-{0}ErrorDetails:{1}”,(int)response.StatusCode,response.ReasonPhrase));

Page 18: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

}

}

data.Text=result.ToString();

}

Page 19: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

AccessingtheWebAPIfromjQueryFromanHTML5Webapplication,youcanuse jQuery todirectlyaccess theWebAPI.You call theAPI by using the getJSON()method to extract the business object from theresult. jQuery can identify internal fields associated with the business object, such asdata[i].Price.

ThecodesnippetinListing5retrievesdatafromourProductAPImethodsanddisplaysthedatainatabularformat.Referthecodecommentstounderstandthecodesnippet.Listing5:UsingjQuerytoretrievedatafromtheWebAPImethods

<head>

<title></title>

<scriptsrc=“Scripts/jquery-1.8.2.js”></script>

<scripttype=“text/javascript”>

$.getJSON(“api/products”,

function(data){

//Clearthedivdisplayingtheresult

$(“#productView”).empty();

//Createatableandappendthetablebody

var$table=$(‘<tableborder=“2”>’);

var$tbody=$table.append(‘<tbody/>’).children(‘tbody’);

//data-returnvaluefromtheWebAPImethod

for(vari=0;i<data.length;i++){

//addanewrowtothetable

var$trow=$tbody.append(‘<tr/>’).children(‘tr:last’);

//addanewcolumntodisplayName

var$tcol=$trow.append(“<td/>”).children(‘td:last’)

.append(data[i].Name);

//addanewcolumntodisplayCategory

var$tcol=$trow.append(“<td/>”).children(‘td:last’)

.append(data[i].Category);

//addanewcolumntodisplayPrice

var$tcol=$trow.append(“<td/>”).children(‘td:last’)

.append(data[i].Price);

}

Page 20: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

//displaythetableinthediv

$table.appendTo(‘#productView’);

});

</script>

</head>

<body>

<divid=“productView”></div>

</body>

</html>

Page 21: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

PassingaParameterfromjQueryIn addition to retrieving data from theWebAPImethods, you can use jQuery to passparameters back to the Web API. jQuery supports several methods for passing theparameters.Thefirstapproachistouseseparateparameterset.Thefollowingcodesnippetdemonstrateshowtopassasingleparameter:

$.getJSON(“api/products”,

{selectedId:‘4’},

function(data){….});

Youcanalsopassmultipleparameterswithinaparameterset,asshowninthefollowingsnippet:

$.getJSON(“api/products”,

{selectedId:‘4’,name:‘TV’},

function(data){….});

AnotherapproachyoucantakeistopassaparameterbyappendingittotheURLquerystring,asshowninthefollowingsnippet:$.getJSON(“api/products?selectedId=4”,

function(data){….});

First approach separates the query string or parameter passing from the URL and isappropriate for complexormultiple data passing.Second approach ismore suitable forpassingoneortwoparameters.

Page 22: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET
Page 23: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

ScaffoldingwithWebAPIASP.NET Scaffolding is a code generation framework for ASP.NETWeb applications.Visual Studio includes pre-installed code generators for MVC and Web API projects.VisualStudioautomaticallygeneratestheAPIcoderequiredtoperformvariousoperationsonthespecifiedmodelordatasource.

Page 24: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

ScaffoldontheEntityFrameworkTo demonstrate how scaffolding works in a Web API project, we can use the EntityFrameworktodefineourdatabaseandgeneratetheWebAPImethods.First,weneedtoaddanADO.NETentitydatamodelthatdefinesthedata.

Add an ADO.NET Entity DataModel to the project using the Add new Item contextmenu.

Figure7:NewADO.NETEntityDataModel

Select the Empty EF designer model option to define the models using Model Firstapproach.

NOTE: For more details on different entity framework approaches, refer DifferentApproachesofEntityFramework

Figure8:EmptyEFDesignermodel

Design themodels using the EntityDataModel designer. For the sample, use the data

Page 25: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

modelbasedontwotables,CourseandStatus,asshowninthenextFigure.

Figure9:AddinganentitydatamodelbasedontheCourseandStatustables

Afterwedefinethedatamodel,wecangeneratetheWebAPIcontrollerthatcorrespondstothemodel.RebuildtheapplicationtogeneratethecodecontextcorrespondingtotheEFdatamodel.Right-clickControllerandthenclickAddController,whichlunchestheAddScaffolddialog box. Select theWebAPI 2Controllerwith actions, usingEntityFrameworkoptionandclickAdd.

Figure10:AddingacontrollerbasedontheEFdatamodel

This will open theAddController window. Select the Course model from the list ofavailable models and select the container corresponding to the course model for DataContext.

Page 26: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

Figure11:AddController

IfyouareplanningtoexecutetheWebAPImethodsinasynchronousmanner,selecttheUseasynccontrolleractionscheckbox.ClickonAddtoaddthenewWebAPIcontroller,courseController basedon actions related to theCoursemodel.Samewayadd theWebAPImethodsfortheStatusmodeltoo.

Listing6showstheautomaticcodegeneratedfortheCourseControllerAPIcontroller.Noticethatitcontainsmethodstosupportget,put,post,anddeleteoperationsthatcorrespondtotheselectedmodel.Listing6:CodegeneratedfortheCourseControllerAPIcontroller

publicclassCoursesController:ApiController

{

privateApplicationDbContextdb=newApplicationDbContext();

//GET:api/Courses

publicIQueryable<Course>GetCourses()

{

returndb.Courses;

}

//GET:api/Courses/5

[ResponseType(typeof(Course))]

publicIHttpActionResultGetCourse(intid)

{

Coursecourse=db.Courses.Find(id);

if(course==null)

{

returnNotFound();

}

Page 27: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

returnOk(course);

}

//PUT:api/Courses/5

[ResponseType(typeof(void))]

publicIHttpActionResultPutCourse(intid,Coursecourse)

{

if(!ModelState.IsValid)

{

returnBadRequest(ModelState);

}

if(id!=course.CourseId)

{

returnBadRequest();

}

db.Entry(course).State=System.Data.Entity.EntityState.Modified;

try

{

db.SaveChanges();

}

catch(DbUpdateConcurrencyException)

{

if(!CourseExists(id))

{

returnNotFound();

}

else

{

throw;

}

}

returnStatusCode(HttpStatusCode.NoContent);

}

Page 28: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

//POST:api/Courses

[ResponseType(typeof(Course))]

publicIHttpActionResultPostCourse(Coursecourse)

{

if(!ModelState.IsValid)

{

returnBadRequest(ModelState);

}

db.Courses.Add(course);

db.SaveChanges();

returnCreatedAtRoute(“DefaultApi”,new{id=course.CourseId},course);

}

//DELETE:api/Courses/5

[ResponseType(typeof(Course))]

publicIHttpActionResultDeleteCourse(intid)

{

Coursecourse=db.Courses.Find(id);

if(course==null)

{

returnNotFound();

}

db.Courses.Remove(course);

db.SaveChanges();

returnOk(course);

}

protectedoverridevoidDispose(booldisposing)

{

if(disposing)

{

db.Dispose();

}

Page 29: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

base.Dispose(disposing);

}

privateboolCourseExists(intid)

{

returndb.Courses.Count(e=>e.CourseId==id)>0;

}

}

TheWebAPIscaffoldingfeaturereducesthedevelopmenteffortrequiredtogeneratetheAPI methods necessary to perform CRUD (create, read, update, delete) operations indifferentmodels.

Page 30: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET
Page 31: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

RoutinginASP.NETWebAPIWebAPIusesroutingtomatchuniformresourceidentifiers(URIs)tovariousactions.TheWebApiConfigfile,locatedinsidetheApp_StartnodeinSolutionExplorer,definesthedefaultroutingmechanismusedbyWebAPI.ThemechanismisbasedonacombinationofHTTPmethod, action, and attribute. However, we can define our own routing mechanism tosupportmeaningfulURIs.

For example, in our sample Web API project, we use /api/Products to retrieve productdetails. However, we can instead use api/Products/GetAllProducts by modifying the defaultroutinglogictoinclude{action}aspartoftheURI,asshowninthefollowingcodesnippet:config.Routes.MapHttpRoute(

name:“DefaultApi”,

routeTemplate:“api/{controller}/{action}/{id}”,

defaults:new{id=RouteParameter.Optional}

);

Afterweupdatetheroute,wecanusetheActionNameattributeinourWebAPImethodtospecifytheactionname,asthefollowsnippetshows:

[ActionName(“GetAllProducts”)]

publicIEnumerable<Product>GetAllProducts()

{……………………………..}

NOTE:Use the [NonAction] attribute to indicate that theWebAPImethod is not anAPIactionmethod.

We can also use an HTTP method or Acceptverbs attribute to specify the HTTP actionrequired to access the Web API method. For example, the following snippet uses theHttpGetandHttpPostmethods:

[HttpGet]

publicIEnumerable<Product>GetProducts(intselectedId)

{…………..}

[HttpPost]

publicvoidAddProduct(Productp)

{…………..}

Formultiplemethods,usetheAcceptsverbsattribute,asshowninthefollowingsnippet:[AcceptVerbs(“GET”,“PUT”)]

publicIEnumerable<Product>GetProducts(intselectedId)

Page 32: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

{…………..}

Page 33: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

AttributeRoutingWeb API 2 introduced the attribute routing. Earlier versions support the conventionalroutingmechanismdiscussed in last section.This approach is good formaintaining theroutinglogicinoneplaceandapplyconsistentlyacrosstheapplication.But,thisapproachlacktheflexibilityofdefiningtheroutingforobjectswithsubgroupslikeProductsmayhave different categories, bookswill have authors, and so on.Attribute routing addressthisissueandprovidestheflexibilitytodefinetheroutingingranularlevels.

Enabletherouting

ForenablingtheattributeroutinginWebAPI,calltheMapHttpAttributeRoutesduringtheconfiguration. Open theWebApiConfig file, located inside the App_Start node in SolutionExplorer.Followingentrydefinetheattributeroutingcapability.

//WebAPIroutes

config.MapHttpAttributeRoutes();

Thisentrywillbeavailable inASP.NETMVC5basedproject; ifnot availableadd theabovestatementtoenabletheattributerouting.

AddRoute

AddtherouteattributetotheWebAPImethodtodefineattributeroutingforspecificWebAPImethods[Route(“ProductDetail/{selectedId}”)]

publicIEnumerable<Product>GetProducts(intselectedId)

{………………………..}

Above method can be accessed now using http://localhost:59509/ProductDetail/2.NoticethatthenewURLnotevenhavetheapiorcontrollernames.

RoutePrefix

Most of the time the controller will have the same format for the routes for all themethods.publicclassProductsController:ApiController

{

[Route(“api/products”)]

publicIEnumerable<Product>GetProducts(){…}

[Route(“api/products/{id}”)]

publicProductGetProduct(intid){…}

}

WecanuseaRoutePrefixtoavoidtheduplicateentryofprefixesforthewebAPImethodRouteattributes.[RoutePrefix(“api/products”)]

Page 34: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

publicclassProductsController:ApiController

{

[Route(””)]

publicIEnumerable<Product>GetProducts(){…}

[Route(“{id}”)]

publicProductGetProduct(intid){…}

}

RoutePrefixwillbeappliedincontrollerlevel.

RouteConstraint

Routeconstraintshelpustorestricttheparameterprocessing.Considertheaboutattributeroutingwherewehavedefinedaparameter‘id’,withoutanyconstraint.Eveniftheclientsendastringvalue,theroutingwilltrytomatchtheparameterandthrowanexceptiondueto typemismatch.Toavoid such runtimeexceptions,wecandefine a constraint for therouteparameters.

Routeconstraintwillbedefinedas

{parameter:constraint}

Eg:-

Integerconstraint-{id:int}

Integerwithmaximumvalueas25–{id:max(25)}

Datetimeconstraint–{startDate:datetime}

Guidconstraint–{id:guid}

We can applymultiple constraints to a parameter by separating each constraint using acolon.

{id:int:min(1)}–indicateanintegerwithaminimumvalueof1.

Page 35: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET
Page 36: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

ImplementingMultipleSerializationOptionsWeb API supports numerous serialization methods, including XML and JSON. In thesectionstofollow,we’lltakeacloserlookathowtoimplementthesethreemethodsandthen compare their behavior. Before doing that, however, let’smodify the sampleWebAPIprojecttoreturnbulkdatasowecanbetterunderstandandcomparetheperformanceof the serializationmethods.Listing7 showshow theGetProducts()methodupdated toreturnbulkdata.

privatevoidGetProducts()

{

for(inti=0;i<5000;i++)

{

products.Add(newProduct{Id=i,Name=“Product-”+i,

Category=“TheASP.NETandVisualWebDeveloperteamshavereleasedtheASP.NETandWebTools2012.2update,whichextendstheexistingASP.NETruntimeandaddsnewwebtoolingtoVisualStudio2012.WhetheryouuseWebForms,MVC,WebAPI,oranyotherASP.NETtechnology,thereissomethingcoolinthisupdateforyou.”

Price=1});

}

}

Listing7:UpdatingtheGetProducts()method

Page 37: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

UsingJSONSerializationWebAPIusesJSONasitsdefaultserializationmethod.Asaresult,whenyouruntheWebAPIproject, the results are automatically returned in the JSONformat.For example, toretrieve details from Products, you need only use the syntax http://<<server>>:<<port>>/api/ProductstoreturntheresultsintheJSONformat.

Page 38: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

UsingXMLSerializationTo use the XML serialization method in a Web API project, you must modify theGlobal.asax fileby inserting the following two linesofcodeat theendofApplication_Start()method:GlobalConfiguration.Configuration.Formatters.RemoveAt(0);

GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer=true;

After implementing theXMLserializationmethod,youcanretrievedetails fromProductsbyusingthesyntaxhttp://<<server>>:<<port>>/api/Products,thesamesyntaxusedforJSON.

Page 39: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET
Page 40: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

HelpPageGenerationfromXMLDocumentationBy default, Web API provides help pages related to the API methods defined in theproject.WecangeneratethehelppagesfromtheXMLdocumentationsprovidedaspartofthemethoddefinition.

Tocreate thehelppages, expand theAreas node inSolutionExplorer and thenopen theHelpPageConfig.csfile

Figure12:AccessingtheHelpPageConfig.csfileinthesampleWebAPIproject

IntheHelpPageConfig.csfile,un-commentthefollowingstatement:config.SetDocumentationProvider(newXmlDocumentationProvider(HttpContext.Current.Server.MapPath(“~/App_Data/XmlDocument.xml”

Next,enableXMLdocumentationbyselectingtheXMLdocumentationfileoptionintheBuildsectionoftheproject’sproperties,asshowninFigure11.CopythefilenamespecifiedintheconfigfiletotheXMLdocumentationfileoption.

Figure13:EnablingtheXMLdocumentationfileintheWebAPIproject

Now,let’saddtheXMLdocumentationtooursampleAPIcontroller,asshowninListing9.Justbeforeeachmethoddefinition,specify“///”togetthedefaultXMLdocumentationforthemethod.Modifyfurtherwithmorespecificcomments.

///<summary>

///GetAllproductsforourSample

///</summary>

///<returns></returns>

publicIEnumerable<Product>GetAllProducts()

{

–––––

}

Page 41: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

///<summary>

///Returnthedetailsofselectedproductdependsontheproductidpassed.

///</summary>

///<paramname=“selectedId”></param>

///<paramname=“name”></param>

///<returns></returns>

publicIEnumerable<Product>GetProducts(intselectedId)

{

––––––

}

Listing9:AddingXMLdocumentationtothesampleAPIcontroller

Onceyou’veupdatedthecontroller,runtheapplicationandnavigatetoAPIlinkatthetop-rightcornerofthebrowserscreen,asshowninnextFigure.

Figure14:ViewingtheAPIlinkintheapplicationwindow

ClicktheAPI linktoopenthehelppage.NoticetheXMLdocumentationcommentsthathadbeenaddedtothecontroller,asshowninnextFigure.

Figure15:ViewingthecommentsintheWebAPIhelpfile

Page 42: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

WCFviaWebAPIWCFsupportsnumerousprotocolsandmessagingformats.WithWebAPI,wecancreateonly HTTP-based services. Obviously, we can create HTTP services with WCF, butthey’re hidden inside different abstraction layers. In addition, implementation is morecomplexwithWCFthanwithWebAPI.HTTPimplementedonWCFusestheHTTPpostmodel,andwemaynotbeabletousethemainfeaturesassociatedwithHTTPprotocolssuchasCachingandStatusCode.ByusingWebAPI,wecanperformallactivities likeget,post,andput,andwecanusedifferentHTTPprotocolfeatures.

WCF requires complex binding and addressmanipulation and configurations, butWebAPI is straightforwardandsimple touse.WebAPI isalsoabetterchoice forRESTfullservicecreation.YoucanfindadetailedcomparisonbetweenWCFandWebAPIin theMSDNarticle“WCFandASP.NETWebAPI.”

Page 43: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET
Page 44: ASP.NET Web API 2: Beginner Guide - DropPDF1.droppdf.com/files/ItDez/asp-net-web-api-2-beginner-guide-by-ambily-k-k.pdfASP.NET Scaffolding is a code generation framework for ASP.NET

References1. [DifferentApproachesofEntityFramework]

https://www.simple-talk.com/dotnet/.net-framework/different-approaches-of-entity-framework/

2. [WCFandASP.NETWebAPI]http://msdn.microsoft.com/en-us/library/jj823172.aspx