"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Calling Web API from a Windows Phone 8 Application (C#)

by Robert McMurray

In this tutorial, you will learn how to create a complete end-to-end scenario consisting of an ASP.NET Web API application that provides a catalog of books to a Windows Phone 8 application.

Overview

RESTful services like ASP.NET Web API simplify the creation of HTTP-based applications for developers by abstracting the architecture for server-side and client-side applications. Instead of creating a proprietary socket-based protocol for communication, Web API developers simply need to publish the requisite HTTP methods for their application, (for example: GET, POST, PUT, DELETE), and client application developers only need to consume the HTTP methods that are necessary for their application.

In this end-to-end tutorial, you will learn how to use Web API to create the following projects:

Prerequisites

[!NOTE] If you are going to test the connectivity between Web API and Windows Phone 8 projects on your local system, you will need to follow the instructions in the Connecting the Windows Phone 8 Emulator to Web API Applications on a Local Computer article to set up your testing environment.

### Step 1: Creating the Web API Bookstore Project

The first step of this end-to-end tutorial is to create a Web API project that supports all of the CRUD operations; note that you will add the Windows Phone application project to this solution in Step 2 of this tutorial.

  1. Open Visual Studio 2013.
  2. Click File, then New, and then Project.
  3. When the New Project dialog box is displayed, expand Installed, then Templates, then Visual C#, and then Web.

    Click image to expand
  4. Highlight ASP.NET Web Application, enter BookStore for the project name, and then click OK.
  5. When the New ASP.NET Project dialog box is displayed, select the Web API template, and then click OK.

    Click image to expand
  6. When the Web API project opens, remove the sample controller from the project:

    1. Expand the Controllers folder in the solution explorer.
    2. Right-click the ValuesController.cs file, and then click Delete.
    3. Click OK when prompted to confirm the deletion.
  7. Add an XML data file to the Web API project; this file contains the contents of the bookstore catalog:

    1. Right-click the App_Data folder in the solution explorer, then click Add, and then click New Item.
    2. When the Add New Item dialog box is displayed, highlight the XML File template.
    3. Name the file Books.xml, and then click Add.
    4. When the Books.xml file is opened, replace the code in the file with the XML from the sample books.xml file on MSDN:

      [!code-xmlMain]
         1:  <?xml version="1.0" encoding="utf-8"?>
         2:  <catalog>
         3:    <book id="bk101">
         4:      <author>Gambardella, Matthew</author>
         5:      <title>XML Developer's Guide</title>
         6:      <genre>Computer</genre>
         7:      <price>44.95</price>
         8:      <publish_date>2000-10-01</publish_date>
         9:      <description>
        10:        An in-depth look at creating applications
        11:        with XML.
        12:      </description>
        13:    </book>
        14:    <book id="bk102">
        15:      <author>Ralls, Kim</author>
        16:      <title>Midnight Rain</title>
        17:      <genre>Fantasy</genre>
        18:      <price>5.95</price>
        19:      <publish_date>2000-12-16</publish_date>
        20:      <description>
        21:        A former architect battles corporate zombies,
        22:        an evil sorceress, and her own childhood to become queen
        23:        of the world.
        24:      </description>
        25:    </book>
        26:    <book id="bk103">
        27:      <author>Corets, Eva</author>
        28:      <title>Maeve Ascendant</title>
        29:      <genre>Fantasy</genre>
        30:      <price>5.95</price>
        31:      <publish_date>2000-11-17</publish_date>
        32:      <description>
        33:        After the collapse of a nanotechnology
        34:        society in England, the young survivors lay the
        35:        foundation for a new society.
        36:      </description>
        37:    </book>
        38:    <book id="bk104">
        39:      <author>Corets, Eva</author>
        40:      <title>Oberon's Legacy</title>
        41:      <genre>Fantasy</genre>
        42:      <price>5.95</price>
        43:      <publish_date>2001-03-10</publish_date>
        44:      <description>
        45:        In post-apocalypse England, the mysterious
        46:        agent known only as Oberon helps to create a new life
        47:        for the inhabitants of London. Sequel to Maeve
        48:        Ascendant.
        49:      </description>
        50:    </book>
        51:    <book id="bk105">
        52:      <author>Corets, Eva</author>
        53:      <title>The Sundered Grail</title>
        54:      <genre>Fantasy</genre>
        55:      <price>5.95</price>
        56:      <publish_date>2001-09-10</publish_date>
        57:      <description>
        58:        The two daughters of Maeve, half-sisters,
        59:        battle one another for control of England. Sequel to
        60:        Oberon's Legacy.
        61:      </description>
        62:    </book>
        63:    <book id="bk106">
        64:      <author>Randall, Cynthia</author>
        65:      <title>Lover Birds</title>
        66:      <genre>Romance</genre>
        67:      <price>4.95</price>
        68:      <publish_date>2000-09-02</publish_date>
        69:      <description>
        70:        When Carla meets Paul at an ornithology
        71:        conference, tempers fly as feathers get ruffled.
        72:      </description>
        73:    </book>
        74:    <book id="bk107">
        75:      <author>Thurman, Paula</author>
        76:      <title>Splish Splash</title>
        77:      <genre>Romance</genre>
        78:      <price>4.95</price>
        79:      <publish_date>2000-11-02</publish_date>
        80:      <description>
        81:        A deep sea diver finds true love twenty
        82:        thousand leagues beneath the sea.
        83:      </description>
        84:    </book>
        85:    <book id="bk108">
        86:      <author>Knorr, Stefan</author>
        87:      <title>Creepy Crawlies</title>
        88:      <genre>Horror</genre>
        89:      <price>4.95</price>
        90:      <publish_date>2000-12-06</publish_date>
        91:      <description>
        92:        An anthology of horror stories about roaches,
        93:        centipedes, scorpions  and other insects.
        94:      </description>
        95:    </book>
        96:    <book id="bk109">
        97:      <author>Kress, Peter</author>
        98:      <title>Paradox Lost</title>
        99:      <genre>Science Fiction</genre>
       100:      <price>6.95</price>
       101:      <publish_date>2000-11-02</publish_date>
       102:      <description>
       103:        After an inadvertant trip through a Heisenberg
       104:        Uncertainty Device, James Salway discovers the problems
       105:        of being quantum.
       106:      </description>
       107:    </book>
       108:    <book id="bk110">
       109:      <author>O'Brien, Tim</author>
       110:      <title>Microsoft .NET: The Programming Bible</title>
       111:      <genre>Computer</genre>
       112:      <price>36.95</price>
       113:      <publish_date>2000-12-09</publish_date>
       114:      <description>
       115:        Microsoft's .NET initiative is explored in
       116:        detail in this deep programmer's reference.
       117:      </description>
       118:    </book>
       119:    <book id="bk111">
       120:      <author>O'Brien, Tim</author>
       121:      <title>MSXML3: A Comprehensive Guide</title>
       122:      <genre>Computer</genre>
       123:      <price>36.95</price>
       124:      <publish_date>2000-12-01</publish_date>
       125:      <description>
       126:        The Microsoft MSXML3 parser is covered in
       127:        detail, with attention to XML DOM interfaces, XSLT processing,
       128:        SAX and more.
       129:      </description>
       130:    </book>
       131:    <book id="bk112">
       132:      <author>Galos, Mike</author>
       133:      <title>Visual Studio 7: A Comprehensive Guide</title>
       134:      <genre>Computer</genre>
       135:      <price>49.95</price>
       136:      <publish_date>2001-04-16</publish_date>
       137:      <description>
       138:        Microsoft Visual Studio 7 is explored in depth,
       139:        looking at how Visual Basic, Visual C++, C#, and ASP+ are
       140:        integrated into a comprehensive development
       141:        environment.
       142:      </description>
       143:    </book>
       144:  </catalog>
    5. Save and close the XML file.
  8. Add the bookstore model to the Web API project; this model contains the Create, Read, Update, and Delete (CRUD) logic for the bookstore application:

    1. Right-click the Models folder in the solution explorer, then click Add, and then click Class.
    2. When the Add New Item dialog box is displayed, name the class file BookDetails.cs, and then click Add.
    3. When the BookDetails.cs file is opened, replace the code in the file with the following:

      [!code-csharpMain]
         1:  using System;
         2:  using System.Collections.Generic;
         3:  using System.ComponentModel.DataAnnotations;
         4:  using System.Linq;
         5:  using System.Xml;
         6:  using System.Xml.Linq;
         7:  using System.Xml.XPath;
         8:  using System.Web;
         9:   
        10:  namespace BookStore.Models
        11:  {
        12:      /// <summary>
        13:      /// Define a class that will hold the detailed information for a book.
        14:      /// </summary>
        15:      public class BookDetails
        16:      {
        17:          [Required]
        18:          public String Id { get; set; }
        19:          [Required]
        20:          public String Title { get; set; }
        21:          public String Author { get; set; }
        22:          public String Genre { get; set; }
        23:          public Decimal Price { get; set; }
        24:          public DateTime PublishDate { get; set; }
        25:          public String Description { get; set; }
        26:      }
        27:   
        28:      /// <summary>
        29:      /// Define an interface which contains the methods for the book repository.
        30:      /// </summary>
        31:      public interface IBookRepository
        32:      {
        33:          BookDetails CreateBook(BookDetails book);
        34:          IEnumerable<BookDetails> ReadAllBooks();
        35:          BookDetails ReadBook(String id);
        36:          BookDetails UpdateBook(String id, BookDetails book);
        37:          Boolean DeleteBook(String id);
        38:      }
        39:   
        40:      /// <summary>
        41:      /// Define a class based on the book repository interface which contains the method implementations.
        42:      /// </summary>
        43:      public class BookRepository : IBookRepository
        44:      {
        45:          private string xmlFilename = null;
        46:          private XDocument xmlDocument = null;
        47:   
        48:          /// <summary>
        49:          /// Define the class constructor.
        50:          /// </summary>
        51:          public BookRepository()
        52:          {
        53:              try
        54:              {
        55:                  // Determine the path to the books.xml file.
        56:                  xmlFilename = HttpContext.Current.Server.MapPath("~/app_data/books.xml");
        57:                  // Load the contents of the books.xml file into an XDocument object.
        58:                  xmlDocument = XDocument.Load(xmlFilename);
        59:              }
        60:              catch (Exception ex)
        61:              {
        62:                  // Rethrow the exception.
        63:                  throw ex;
        64:              }
        65:          }
        66:   
        67:          /// <summary>
        68:          /// Method to add a new book to the catalog.
        69:          /// Defines the implementation of the POST method.
        70:          /// </summary>
        71:          public BookDetails CreateBook(BookDetails book)
        72:          {
        73:              try
        74:              {
        75:                  // Retrieve the book with the highest ID from the catalog.
        76:                  var highestBook = (
        77:                      from bookNode in xmlDocument.Elements("catalog").Elements("book")
        78:                      orderby bookNode.Attribute("id").Value descending
        79:                      select bookNode).Take(1);
        80:                  // Extract the ID from the book data.
        81:                  string highestId = highestBook.Attributes("id").First().Value;
        82:                  // Create an ID for the new book.
        83:                  string newId = "bk" + (Convert.ToInt32(highestId.Substring(2)) + 1).ToString();
        84:                  // Verify that this book ID does not currently exist.
        85:                  if (this.ReadBook(newId) == null)
        86:                  {
        87:                      // Retrieve the parent element for the book catalog.
        88:                      XElement bookCatalogRoot = xmlDocument.Elements("catalog").Single();
        89:                      // Create a new book element.
        90:                      XElement newBook = new XElement("book", new XAttribute("id", newId));
        91:                      // Create elements for each of the book's data items.
        92:                      XElement[] bookInfo = FormatBookData(book);
        93:                      // Add the element to the book element.
        94:                      newBook.ReplaceNodes(bookInfo);
        95:                      // Append the new book to the XML document.
        96:                      bookCatalogRoot.Add(newBook);
        97:                      // Save the XML document.
        98:                      xmlDocument.Save(xmlFilename);
        99:                      // Return an object for the newly-added book.
       100:                      return this.ReadBook(newId);
       101:                  }
       102:              }
       103:              catch (Exception ex)
       104:              {
       105:                  // Rethrow the exception.
       106:                  throw ex;
       107:              }
       108:              // Return null to signify failure.
       109:              return null;
       110:          }
       111:   
       112:          /// <summary>
       113:          /// Method to retrieve all of the books in the catalog.
       114:          /// Defines the implementation of the non-specific GET method.
       115:          /// </summary>
       116:          public IEnumerable<BookDetails> ReadAllBooks()
       117:          {
       118:              try
       119:              {
       120:                  // Return a list that contains the catalog of book ids/titles.
       121:                  return (
       122:                      // Query the catalog of books.
       123:                      from book in xmlDocument.Elements("catalog").Elements("book")
       124:                      // Sort the catalog based on book IDs.
       125:                      orderby book.Attribute("id").Value ascending
       126:                      // Create a new instance of the detailed book information class.
       127:                      select new BookDetails
       128:                      {
       129:                          // Populate the class with data from each of the book's elements.
       130:                          Id = book.Attribute("id").Value,
       131:                          Author = book.Element("author").Value,
       132:                          Title = book.Element("title").Value,
       133:                          Genre = book.Element("genre").Value,
       134:                          Price = Convert.ToDecimal(book.Element("price").Value),
       135:                          PublishDate = Convert.ToDateTime(book.Element("publish_date").Value),
       136:                          Description = book.Element("description").Value
       137:                      }).ToList();
       138:              }
       139:              catch (Exception ex)
       140:              {
       141:                  // Rethrow the exception.
       142:                  throw ex;
       143:              }
       144:          }
       145:   
       146:          /// <summary>
       147:          /// Method to retrieve a specific book from the catalog.
       148:          /// Defines the implementation of the ID-specific GET method.
       149:          /// </summary>
       150:          public BookDetails ReadBook(String id)
       151:          {
       152:              try
       153:              {
       154:                  // Retrieve a specific book from the catalog.
       155:                  return (
       156:                      // Query the catalog of books.
       157:                      from book in xmlDocument.Elements("catalog").Elements("book")
       158:                      // Specify the specific book ID to query.
       159:                      where book.Attribute("id").Value.Equals(id)
       160:                      // Create a new instance of the detailed book information class.
       161:                      select new BookDetails
       162:                      {
       163:                          // Populate the class with data from each of the book's elements.
       164:                          Id = book.Attribute("id").Value,
       165:                          Author = book.Element("author").Value,
       166:                          Title = book.Element("title").Value,
       167:                          Genre = book.Element("genre").Value,
       168:                          Price = Convert.ToDecimal(book.Element("price").Value),
       169:                          PublishDate = Convert.ToDateTime(book.Element("publish_date").Value),
       170:                          Description = book.Element("description").Value
       171:                      }).Single();
       172:              }
       173:              catch
       174:              {
       175:                  // Return null to signify failure.
       176:                  return null;
       177:              }
       178:          }
       179:   
       180:          /// <summary>
       181:          /// Populates a book BookDetails class with the data for a book.
       182:          /// </summary>
       183:          private XElement[] FormatBookData(BookDetails book)
       184:          {
       185:              XElement[] bookInfo =
       186:              {
       187:                  new XElement("author", book.Author),
       188:                  new XElement("title", book.Title),
       189:                  new XElement("genre", book.Genre),
       190:                  new XElement("price", book.Price.ToString()),
       191:                  new XElement("publish_date", book.PublishDate.ToString()),
       192:                  new XElement("description", book.Description)
       193:              };
       194:              return bookInfo;
       195:          }
       196:   
       197:          /// <summary>
       198:          /// Method to update an existing book in the catalog.
       199:          /// Defines the implementation of the PUT method.
       200:          /// </summary>
       201:          public BookDetails UpdateBook(String id, BookDetails book)
       202:          {
       203:              try
       204:              {
       205:                  // Retrieve a specific book from the catalog.
       206:                  XElement updateBook = xmlDocument.XPathSelectElement(String.Format("catalog/book[@id='{0}']", id));
       207:                  // Verify that the book exists.
       208:                  if (updateBook != null)
       209:                  {
       210:                      // Create elements for each of the book's data items.
       211:                      XElement[] bookInfo = FormatBookData(book);
       212:                      // Add the element to the book element.
       213:                      updateBook.ReplaceNodes(bookInfo);
       214:                      // Save the XML document.
       215:                      xmlDocument.Save(xmlFilename);
       216:                      // Return an object for the updated book.
       217:                      return this.ReadBook(id);
       218:                  }
       219:              }
       220:              catch (Exception ex)
       221:              {
       222:                  // Rethrow the exception.
       223:                  throw ex;
       224:              }
       225:              // Return null to signify failure.
       226:              return null;
       227:          }
       228:   
       229:          /// <summary>
       230:          /// Method to remove an existing book from the catalog.
       231:          /// Defines the implementation of the DELETE method.
       232:          /// </summary>
       233:          public Boolean DeleteBook(String id)
       234:          {
       235:              try
       236:              {
       237:                  if (this.ReadBook(id) != null)
       238:                  {
       239:                      // Remove the specific child node from the catalog.
       240:                      xmlDocument
       241:                          .Elements("catalog")
       242:                          .Elements("book")
       243:                          .Where(x => x.Attribute("id").Value.Equals(id))
       244:                          .Remove();
       245:                      // Save the XML document.
       246:                      xmlDocument.Save(xmlFilename);
       247:                      // Return a success status.
       248:                      return true;
       249:                  }
       250:                  else
       251:                  {
       252:                      // Return a failure status.
       253:                      return false;
       254:                  }
       255:              }
       256:              catch (Exception ex)
       257:              {
       258:                  // Rethrow the exception.
       259:                  throw ex;
       260:              }
       261:          }
       262:      }
       263:  }
    4. Save and close the BookDetails.cs file.
  9. Add the bookstore controller to the Web API project:

    1. Right-click the Controllers folder in the solution explorer, then click Add, and then click Controller.
    2. When the Add Scaffold dialog box is displayed, highlight Web API 2 Controller - Empty, and then click Add.
    3. When the Add Controller dialog box is displayed, name the controller BooksController, and then click Add.
    4. When the BooksController.cs file is opened, replace the code in the file with the following:

      [!code-csharpMain]
         1:  using System;
         2:  using System.Collections.Generic;
         3:  using System.Linq;
         4:  using System.Net;
         5:  using System.Net.Http;
         6:  using System.Web.Http;
         7:  using BookStore.Models;
         8:   
         9:  namespace BookStore.Controllers
        10:  {
        11:      public class BooksController : ApiController
        12:      {
        13:          private BookRepository repository = null;
        14:   
        15:          // Define the class constructor.
        16:          public BooksController()
        17:          {
        18:              this.repository = new BookRepository();
        19:          }
        20:   
        21:          /// <summary>
        22:          /// Method to retrieve all of the books in the catalog.
        23:          /// Example: GET api/books
        24:          /// </summary>
        25:          [HttpGet]
        26:          public HttpResponseMessage Get()
        27:          {
        28:              IEnumerable<BookDetails> books = this.repository.ReadAllBooks();
        29:              if (books != null)
        30:              {
        31:                  return Request.CreateResponse<IEnumerable<BookDetails>>(HttpStatusCode.OK, books);
        32:              }
        33:              else
        34:              {
        35:                  return Request.CreateResponse(HttpStatusCode.NotFound);
        36:              }
        37:          }
        38:   
        39:          /// <summary>
        40:          /// Method to retrieve a specific book from the catalog.
        41:          /// Example: GET api/books/5
        42:          /// </summary>
        43:          [HttpGet]
        44:          public HttpResponseMessage Get(String id)
        45:          {
        46:              BookDetails book = this.repository.ReadBook(id);
        47:              if (book != null)
        48:              {
        49:                  return Request.CreateResponse<BookDetails>(HttpStatusCode.OK, book);
        50:              }
        51:              else
        52:              {
        53:                  return Request.CreateResponse(HttpStatusCode.NotFound);
        54:              }
        55:          }
        56:   
        57:          /// <summary>
        58:          /// Method to add a new book to the catalog.
        59:          /// Example: POST api/books
        60:          /// </summary>
        61:          [HttpPost]
        62:          public HttpResponseMessage Post(BookDetails book)
        63:          {
        64:              if ((this.ModelState.IsValid) && (book != null))
        65:              {
        66:                  BookDetails newBook = this.repository.CreateBook(book);
        67:                  if (newBook != null)
        68:                  {
        69:                      var httpResponse = Request.CreateResponse<BookDetails>(HttpStatusCode.Created, newBook);
        70:                      string uri = Url.Link("DefaultApi", new { id = newBook.Id });
        71:                      httpResponse.Headers.Location = new Uri(uri);
        72:                      return httpResponse;
        73:                  }
        74:              }
        75:              return Request.CreateResponse(HttpStatusCode.BadRequest);
        76:          }
        77:   
        78:          /// <summary>
        79:          /// Method to update an existing book in the catalog.
        80:          /// Example: PUT api/books/5
        81:          /// </summary>
        82:          [HttpPut]
        83:          public HttpResponseMessage Put(String id, BookDetails book)
        84:          {
        85:              if ((this.ModelState.IsValid) && (book != null) && (book.Id.Equals(id)))
        86:              {
        87:                  BookDetails modifiedBook = this.repository.UpdateBook(id, book);
        88:                  if (modifiedBook != null)
        89:                  {
        90:                      return Request.CreateResponse<BookDetails>(HttpStatusCode.OK, modifiedBook);
        91:                  }
        92:                  else
        93:                  {
        94:                      return Request.CreateResponse(HttpStatusCode.NotFound);
        95:                  }
        96:              }
        97:              return Request.CreateResponse(HttpStatusCode.BadRequest);
        98:          }
        99:   
       100:          /// <summary>
       101:          /// Method to remove an existing book from the catalog.
       102:          /// Example: DELETE api/books/5
       103:          /// </summary>
       104:          [HttpDelete]
       105:          public HttpResponseMessage Delete(String id)
       106:          {
       107:              BookDetails book = this.repository.ReadBook(id);
       108:              if (book != null)
       109:              {
       110:                  if (this.repository.DeleteBook(id))
       111:                  {
       112:                      return Request.CreateResponse(HttpStatusCode.OK);
       113:                  }
       114:              }
       115:              else
       116:              {
       117:                  return Request.CreateResponse(HttpStatusCode.NotFound);
       118:              }
       119:              return Request.CreateResponse(HttpStatusCode.BadRequest);
       120:          }
       121:      }
       122:  }
    5. Save and close the BooksController.cs file.
  10. Build the Web API application to check for errors.

### Step 2: Adding the Windows Phone 8 Bookstore Catalog Project

The next step of this end-to-end scenario is to create the catalog application for Windows Phone 8. This application will use the Windows Phone Databound App template for the default user interface, and it will use the Web API application that you created in Step 1 of this tutorial as the data source.

  1. Right-click the BookStore solution in the in the solution explorer, then click Add, and then New Project.
  2. When the New Project dialog box is displayed, expand Installed, then Visual C#, and then Windows Phone.
  3. Highlight Windows Phone Databound App, enter BookCatalog for the name, and then click OK.
  4. Add the Json.NET NuGet package to the BookCatalog project:

    1. Right-click References for the BookCatalog project in the solution explorer, and then click Manage NuGet Packages.
    2. When the Manage NuGet Packages dialog box is displayed, expand the Online section, and highlight nuget.org.
    3. Enter Json.NET in the search field and click the search icon.
    4. Highlight Json.NET in the search results, and then click Install.
    5. When the installation has completed, click Close.
  5. Add the BookDetails model to the BookCatalog project; this contains a generic model of the bookstore class:

    1. Right-click the BookCatalog project in the solution explorer, then click Add, and then click New Folder.
    2. Name the new folder Models.
    3. Right-click the Models folder in the solution explorer, then click Add, and then click Class.
    4. When the Add New Item dialog box is displayed, name the class file BookDetails.cs, and then click Add.
    5. When the BookDetails.cs file is opened, replace the code in the file with the following:

      [!code-csharpMain]
         1:  using System;
         2:  using System.Text;
         3:   
         4:  namespace BookCatalog.Models
         5:  {
         6:      /// <summary>
         7:      /// Define a class that will hold the detailed information for a book.
         8:      /// </summary>
         9:      public class BookDetails
        10:      {
        11:          public String Id { get; set; }
        12:          public String Title { get; set; }
        13:          public String Author { get; set; }
        14:          public String Genre { get; set; }
        15:          public Decimal Price { get; set; }
        16:          public DateTime PublishDate { get; set; }
        17:          public String Description { get; set; }
        18:      }
        19:  }
    6. Save and close the BookDetails.cs file.
  6. Update the MainViewModel.cs class to include the functionality to communicate with the BookStore Web API application:

    1. Expand the ViewModels folder in the solution explorer, and then double-click the MainViewModel.cs file.
    2. When the the MainViewModel.cs file is opened, replace the code in the file with the following; note that you will need to update the value of the apiUrl constant with the actual URL of your Web API:

      [!code-csharpMain]
         1:  using System;
         2:  using System.Collections.ObjectModel;
         3:  using System.ComponentModel;
         4:  using System.Net;
         5:  using System.Net.NetworkInformation;
         6:  using BookCatalog.Resources;
         7:  using System.Collections.Generic;
         8:  using Newtonsoft.Json;
         9:  using BookCatalog.Models;
        10:   
        11:  namespace BookCatalog.ViewModels
        12:  {
        13:      public class MainViewModel : INotifyPropertyChanged
        14:      {
        15:          const string apiUrl = @"http://www.contoso.com/api/Books";
        16:   
        17:          public MainViewModel()
        18:          {
        19:              this.Items = new ObservableCollection<ItemViewModel>();
        20:          }
        21:   
        22:          /// <summary>
        23:          /// A collection for ItemViewModel objects.
        24:          /// </summary>
        25:          public ObservableCollection<ItemViewModel> Items { get; private set; }
        26:   
        27:          public bool IsDataLoaded
        28:          {
        29:              get;
        30:              private set;
        31:          }
        32:   
        33:          /// <summary>
        34:          /// Creates and adds a few ItemViewModel objects into the Items collection.
        35:          /// </summary>
        36:          public void LoadData()
        37:          {
        38:              if (this.IsDataLoaded == false)
        39:              {
        40:                  this.Items.Clear();
        41:                  this.Items.Add(new ItemViewModel() { ID = "0", LineOne = "Please Wait...", LineTwo = "Please wait while the catalog is downloaded from the server.", LineThree = null });
        42:                  WebClient webClient = new WebClient();
        43:                  webClient.Headers["Accept"] = "application/json";
        44:                  webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadCatalogCompleted);
        45:                  webClient.DownloadStringAsync(new Uri(apiUrl));
        46:              }
        47:          }
        48:   
        49:          private void webClient_DownloadCatalogCompleted(object sender, DownloadStringCompletedEventArgs e)
        50:          {
        51:              try
        52:              {
        53:                  this.Items.Clear();
        54:                  if (e.Result != null)
        55:                  {
        56:                      var books = JsonConvert.DeserializeObject<BookDetails[]>(e.Result);
        57:                      int id = 0;
        58:                      foreach (BookDetails book in books)
        59:                      {
        60:                          this.Items.Add(new ItemViewModel()
        61:                          {
        62:                              ID = (id++).ToString(),
        63:                              LineOne = book.Title,
        64:                              LineTwo = book.Author,
        65:                              LineThree = book.Description.Replace("\n", " ")
        66:                          });
        67:                      }
        68:                      this.IsDataLoaded = true;
        69:                  }
        70:              }
        71:              catch (Exception ex)
        72:              {
        73:                  this.Items.Add(new ItemViewModel()
        74:                  {
        75:                      ID = "0",
        76:                      LineOne = "An Error Occurred",
        77:                      LineTwo = String.Format("The following exception occured: {0}", ex.Message),
        78:                      LineThree = String.Format("Additional inner exception information: {0}", ex.InnerException.Message)
        79:                  });
        80:              }
        81:          }
        82:   
        83:          public event PropertyChangedEventHandler PropertyChanged;
        84:          private void NotifyPropertyChanged(String propertyName)
        85:          {
        86:              PropertyChangedEventHandler handler = PropertyChanged;
        87:              if (null != handler)
        88:              {
        89:                  handler(this, new PropertyChangedEventArgs(propertyName));
        90:              }
        91:          }
        92:      }
        93:  }
    3. Save and close the MainViewModel.cs file.
  7. Update the MainPage.xaml file to customize the application name:

    1. Double-click the MainPage.xaml file in the solution explorer.
    2. When the the MainPage.xaml file is opened, locate the following lines of code:

      [!code-xmlMain]
         1:  <StackPanel Grid.Row="0" Margin="12,17,0,28">
         2:      <TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/> 
         3:      <TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
         4:  </StackPanel>
    3. Replace those lines with the following:

      [!code-xmlMain]
         1:  <StackPanel Grid.Row="0" Margin="12,17,0,28">
         2:      <TextBlock Text="Book Store" Style="{StaticResource PhoneTextTitle1Style}"/> 
         3:      <TextBlock Text="Current Catalog" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle2Style}"/>
         4:  </StackPanel>
    4. Save and close the MainPage.xaml file.
  8. Update the DetailsPage.xaml file to customize the displayed items:

    1. Double-click the DetailsPage.xaml file in the solution explorer.
    2. When the the DetailsPage.xaml file is opened, locate the following lines of code:

      [!code-xmlMain]
         1:  <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
         2:      <TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
         3:      <TextBlock Text="{Binding LineOne}" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
         4:  </StackPanel>
    3. Replace those lines with the following:

      [!code-xmlMain]
         1:  <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
         2:      <TextBlock Text="Book Store" Style="{StaticResource PhoneTextTitle1Style}"/>
         3:      <TextBlock Text="{Binding LineOne}" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle2Style}"/>
         4:  </StackPanel>
    4. Save and close the DetailsPage.xaml file.
  9. Build the Windows Phone application to check for errors.

Step 3: Testing the End-to-End Solution

As mentioned in the Prerequisites section of this tutorial, when you are testing the connectivity between Web API and Windows Phone 8 projects on your local system, you will need to follow the instructions in the Connecting the Windows Phone 8 Emulator to Web API Applications on a Local Computer article to set up your testing environment.

Once you have the testing environment configured, you will need to set the Windows Phone application as the startup project. To do so, highlight the BookCatalog application in the solution explorer, and then click Set as StartUp Project:

Click image to expand

When you press F5, Visual Studio will start both the Windows Phone Emulator, which will display a ???Please Wait??? message while the application data is retrieved from your Web API:

Click image to expand

If everything is successful, you should see the catalog displayed:

Click image to expand

If you tap on any book title, the application will display the book description:

Click image to expand

If the application cannot communicate with your Web API, an error message will be displayed:

Click image to expand

If you tap on the error message, any additional details about the error will be displayed:

Click image to expand


Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/mobile-clients/calling-web-api-from-a-windows-phone-8-application.htm
< THANKS ME>