How to do it...

  1. Open Visual Studio 2017.
  2. Click File | New | Project to create a project. 
  3. In the New Project dialog box, expand the Other Project Types node in the left pane and select Visual Studio Solutions. In the right pane, select Blank Solution.
  1. In the Name: textbox, type Chapter7.RestAPI and in the Location: textbox select a path from the drop-down box or click on the Browse... button to locate a path:
  1. Click OK.
  2. Now your Solution Explorer (Ctrl + Alt + L) should look like this:
  1. Now, click the right mouse button on the Chapter7.RestAPI label in the Solution Explorer and select Add | New Project.
  2. In the New Project dialog box, expand the Visual C# node.
  1. Select .NET Standard in the left pane and Class Library (.NET Standard) in the right pane:
  1. Now, in the Name: textbox type Chapter7.RestAPI.RestLib, leave the other defaults as they are, and click OK:
  1. Now the Solution Explorer (Ctrl + Alt + L) should look like this:
  1. Now, select Class1.cs in the Solution Explorer and press F2 to rename the file to PostsReader.cs.
  2. Answer Yes to the confirmation dialog box that asks to rename the class name as well.
  3. Now, double-click on the PostsReader.cs label in the Solution Explorer.
  4. Let's scroll up in the code window and add the following using directive:
      using System.Net.Http;
using System.Threading.Tasks;
  1. Now, create this class-wide private variable to hold the URL:
      private string _serviceURL;
  1. Let's create the default constructor to update the previous variable:
      public PostsReader(string serviceURL)
{
_serviceURL = serviceURL;
}
  1. Finally, let's add the method to read from the REST service:
      public async Task<string> GetPostById(int id)
{
string output;

using (var httpClient = new HttpClient())
{

Uri uri = new Uri($"{_serviceURL}/posts/{id}");
using (HttpResponseMessage response =
await httpClient.GetAsync(uri))
{
output = await response.Content.ReadAsStringAsync();
}
}

return output;
}
  1. Press Ctrl + Shift + B for a quick build to check the syntax.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.105.239