0% found this document useful (0 votes)
102 views

Consuming-Web-Services-with-CSharp

This document discusses consuming REST services from C# using HttpClient and RestSharp. It covers sending GET and POST requests with HttpClient asynchronously using async/await. It also discusses converting response content to objects, building query strings, and setting request headers. RestSharp is introduced as an alternative REST API client for .NET.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
102 views

Consuming-Web-Services-with-CSharp

This document discusses consuming REST services from C# using HttpClient and RestSharp. It covers sending GET and POST requests with HttpClient asynchronously using async/await. It also discusses converting response content to objects, building query strings, and setting request headers. RestSharp is introduced as an alternative REST API client for .NET.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Consuming REST

Services from C#

SoftUni Team
Technical Trainers
Software University
http://softuni.bg
Table of Contents
1. Consuming Web Services – Overview
2. Using HttpClient
 Asynchronous API with async/await
3. Using RestSharp

2
HttpClient
 Modern HTTP client for .NET
 Flexible API for accessing HTTP resources
 Has only async methods
 Using the new TAP (Task-based Asynchronous Pattern)

 Sends and receives HTTP requests and responses


 HttpRequestMessage, HttpResponseMessage

 Responses / requests are accessed through async methods

 Can have defaults configured for requests


Sending a GET Request
 *Async().Result blocks the program until a result is returned
string GetAllPostsEndpoint = "http://localhost:64411/api/posts";

var httpClient = new HttpClient();


var response = httpClient.GetAsync(GetAllPostsEndpoint).Result;

var postsJson = response.Content.ReadAsStringAsync().Result;


Console.WriteLine(postsJson);

// [{"id":1,"content":"...","author":"peicho","likes":0},
// {"id":2,"content":"...", ... }]

4
Converting Response to Object
 Microsoft.AspNet.WebApi.Client adds the ReadAsAsync<T>
extension method
var httpClient = new HttpClient();
var response = httpClient.GetAsync(GetAllPostsEndpoint).Result;

var posts = response.Content


.ReadAsAsync<IEnumerable<PostDTO>>().Result;

foreach (PostDTO post in posts) public class PostDTO


{ {
public int Id { get; set; }
Console.WriteLine(post);
public string Content { get; set; }
} public string Author { get; set; }
public int Likes { get; set; }
}
5
Sending a POST Request
var httpClient = new HttpClient(); Manually set custom
httpClient.DefaultRequestHeaders.Add( request header
"Authorization", "Bearer " + "{token}");

var content = new FormUrlEncodedContent(new[]


{
new KeyValuePair<string, string>("content", "nov post"),
new KeyValuePair<string, string>("wallOwnerUsername", "peicho")
});

var response = httpClient


.PostAsync(AddNewPostEndpoint, content).Result;

... Send data in request body

6
Building Query Strings
 HttpClient does not support adding query string parameters
 Can be done with UriBuilder and HttpUtility
const string Endpoint = "api/users/search";
var builder = new UriBuilder(Endpoint);

var query = HttpUtility.ParseQueryString(string.Empty);


query["name"] = "мо";
query["minAge"] = "18";
query["maxAge"] = "50";

builder.Query = query.ToString(); Escapes special characters


Console.WriteLine(builder);
// api/users/search?name=%u043c%u043e&minAge=18&maxAge=50
7
Simple HttpClient Requests
Live Demo
Asynchronous Programming
Synchronous Code
 Synchronous code is executed step by step
10 static void Main()
11 {
int n = int.Parse(..)
12 int n = int.Parse(Console.ReadLine());
13 PrintNumbersInRange(0, 10);
14 Console.WriteLine("Done.");
15 } PrintNumbersInRange()
16
17 static void PrintNumbersInRange(int a, int b)
18 { Console.WriteLine(..)
19 for (int i = a; i <= b; i++)
20 {
21 Console.WriteLine(i); ...
22 }
23 }
10
Asynchronous Code
 Asynchronous programming allows the execution of code
simultaneously
static void Main()
int n = int.Parse(..)
{
int n = int.Parse(Console.ReadLine());

PrintNumbersInRange(0, 10); for (0..10)


var task = Task.Run(() =>
PrintNumbersInRange(10, 20));
Console.WriteLine(..) for (10..20)
Console.WriteLine("Done.");
task.Wait();
} Wait()

11
Tasks with async and await
 The keywords async and await are always used together
 async hints the compiler that the method might run in parallel
 Does not make a method run asynchronously (await makes it)
async void PrintAllPosts(string file, int parts)

 Tells the compiler "this method could wait for a resource or


operation"
 If it starts waiting, return to the calling method
 When the wait is over, go back to called method
12
Tasks with async and await (2)
 await is used in a method which has the async keyword
 Saves the context in a state machine
 Marks waiting for a resource (a task to complete)
 Resource should be a Task<T>
 Returns T result from Task<T> when it completes

await PrintAllPosts("localhost:55231/api/posts");

Returns Task<string>
13
async and await – Example
static void Main()
{
PrintAllPostsAsync("localhost:55231/api/posts");
...
}

static async void PrintAllPostsAsync(string endPoint)


{ The calling thread exits the
var httpClient = new HttpClient(); method on await
Console.WriteLine("Fetching posts...");
var response = await httpClient.GetAsync(endPoint);

var posts = await response.Content.ReadAsAsync<IEnumerable<PostDTO>>();


foreach (var post in posts)
{
Console.WriteLine(post); Everything after that will
} execute when the *Async()
Console.WriteLine("Download successful.");
}
method returns a result
14
Graphical User Interface
Live Demo
RESTSharp
RESTSharp
 Simple REST and HTTP API client for .NET
 Supported in older versions of .NET (before 4.5)

 Available in NuGet
var client = new RestClient();
client.BaseUrl = new Uri("http://localhost:37328/api/");

var request = new RestRequest("students/{id}", Method.GET);


request.AddUrlSegment("id", "5");

var response = client.Execute(request);


Console.WriteLine(response.Content);
Consuming REST Services with C#

https://softuni.bg/courses/web-services-and-cloud/
License
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-ShareAlike 4.0 International" license

 Attribution: this work may contain portions from


 "Web Services and Cloud" course by Telerik Academy under CC-BY-NC-SA license

19
Free Trainings @ Software University
 Software University Foundation – softuni.org
 Software University – High-Quality Education,
Profession and Job for Software Developers
 softuni.bg
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University @ YouTube
 youtube.com/SoftwareUniversity
 Software University Forums – forum.softuni.bg

You might also like