HttpClient

Web page by Kevin Harris of Homer IL

Please contact Kevin Harris of Homer IL concerning this web site

HttpClient

The .NET framework has offered three different classes for consuming HTTP (REST) services. HttpWebRequest (.NET 1.0) was developed first. It gives control over every aspect of the request/response object and does not block the UI thread. However the greater control also introduces greater complexity which can lead to errors in implementation. WebClient (.NET 2.0) was built on top of HttpWebRequest to simplify the common tasks. WebClient requires less code and reduces the likelihood of implementation mistakes. HttpClient requires .NET 4.5+, but provides both power and simplicity, plus support for newer threading features (e.g. await). Also HttpClient is more aligned with REST services and provides more flexibility and extensiblity.

HttpClient provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. HttpClient can be used to call a Web API from a .NET client (e.g. console app, WinForm App, ASP.NET app etc.) by using installing the Web API Client Libraries, which installs with MVC 4.0+, or can be obtained through NuGet. To obtain from the NuGet console, enter:

Install-Package Microsoft.AspNet.WebApi.Client

in a .NET 4.5+ project.

HttpClient supports the more recent async features using Tasks and lambda expressions. The following example illustrates the coding required to implement HttpClient in a console application.

.HttpClient MVC Application

HttpClient MVC Application

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using Newtonsoft.Json;
using System.Net.Http;
using System.Web.Mvc;
//Install-Package Microsoft.AspNet.WebApi.Client
using System.Net.Http.Headers;

namespace GetHubClientMVC.Controllers
{
    public class Entries
    {
        public Entry[] results;
    }
    public class Entry
    {
        [JsonProperty("title")]
        public string Title { get; set; }

        [JsonProperty("number")]
        public string Number { get; set; }
    }

    public class HomeController : Controller
    {
        public async System.Threading.Tasks.Task<ActionResult> Index()
        {
            Entries model = null;
            using (HttpClient client = new HttpClient())
            using (HttpResponseMessage response = await client.GetAsync("https://api.github.com/repos/vmg/redcarpet/issues?state=closed"))
            using (HttpContent content = response.Content)
            {

                client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident / 6.0)");
                client.DefaultRequestHeaders
                    .Accept
                    .Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var readtask = response.Content.ReadAsAsync<Entries>();
                readtask.Wait();
                model = readtask.Result;
            };
            return View(model.results);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

HomeController.cs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@model GetHumClientMVC.Controllers.Entry

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<div>
    <h4>Entry</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Title)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Title)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Number)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Number)
        </dd>

    </dl>
</div>
<p>
    @Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |
    @Html.ActionLink("Back to List", "Index")
</p>

Index.cshtml