Calling a Web API from a. NET Client (C #)

Source: Internet
Author: User

by Mike Wasson+

Download completed Project

This tutorial shows how to call a Web API from a. NET application, using System.Net.Http.HttpClient. +

In this tutorial, we'll write a client application that consumes the following Web API. +

Action HTTP Method Relative URI
Get a product by ID GET /api/products/ID
Create a new product POST /api/products
Update a product PUT /api/products/ID
Delete a product DELETE /api/products/ID
Note

To learn what to implement this API on the server, using the ASP. NET Web API, see Creating a Web API that Supports CRUD Operati Ons. +

For simplicity, the client application in this tutorial is a Windows console application. HttpClient is also supported for Windows Phone and Windows Store apps. For more information, see Writing Web API Client Code for multiple platforms Using Portable Libraries+

+

Create the Console application

In Visual Studio, create a new Windows console application and paste in the following code. +

using System;using System.Net;using System.Net.Http;using System.Net.Http.Headers;using System.Threading.Tasks;namespace HttpClientSample{    class Program    {        static void Main()        {            RunAsync().Wait();        }        static async Task RunAsync()        {            Console.ReadLine();        }    }}

This code provides the skeleton for the application. The Main``RunAsync method and blocks until it completes. The reason for this approach is, and HttpClient methods is async, because they perform network I/O. All of the async tasks is done inside RunAsync . In a console application, it's OK to block the main thread inside of Main . In a GUI application, you should never block the UI thread. +

+

Install the Web API Client Libraries

Use NuGet package Manager to install the Web API Client Libraries package. +

From the Tools menu, select Library Package Manager, and then select Package Manager Console. In the Package Manager Console window, type the following command:+

Install-Package Microsoft.AspNet.WebApi.Client

+

Add a Model Class

ADD the following class to the application:+

namespace HttpClientSample{    public class Product    {        public string Id { get; set; }        public string Name { get; set; }        public decimal Price { get; set; }        public string Category { get; set; }    }}

This class matches the data model used by the Web API. We can use HttpClient to read a Product instance from an HTTP response, without have to write a lot of Deserializ ation code. +

+

Create and Initialize HttpClient

Add a static HttpClient property to the Program class. +

class Program{    // New code:    static HttpClient client = new HttpClient();}
Note

HttpClient is intended to being instantiated once and re-used throughout the life of a application. Especially in server applications, creating a new HttpClient instance for every request would exhaust the number O F sockets available under heavy loads. This would result in socketexception errors. +

To initialize the HttpClient instance, add the following code to the RunAsync method: +

static async Task RunAsync(){    // New code:    client.BaseAddress = new Uri("http://localhost:55268/");    client.DefaultRequestHeaders.Accept.Clear();    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));    Console.ReadLine();}

This code sets the base URI for HTTP requests, and sets the Accept header to ' Application/json ', which tells the server to Send data in JSON format. +

+

Sending a GET request to retrieve a resource

The following code sends a GET request for a product:+

static async Task<Product> GetProductAsync(string path){    Product product = null;    HttpResponseMessage response = await client.GetAsync(path);    if (response.IsSuccessStatusCode)    {        product = await response.Content.ReadAsAsync<Product>();    }    return product;}

The GetAsync method sends the HTTP GET request. The method is asynchronous, because it performs network I/O. When the method completes, it returns a Httpresponsemessage that contains the HTTP response. If the status code in the response is a success code, the response body contains the JSON representation of a product. Call Readasasync to deserialize the JSON payload to a Product instance. The Readasync method is asynchronous because the response body can be arbitrarily large.+

HttpClient does not throw a exception when the HTTP response contains an error code. Instead, the issuccessstatuscode property was false if the status is an error code. If you prefer to treat HTTP error codes as exceptions, call Httpresponsemessage.ensuresuccessstatuscode on the response ob Ject. This method throws an exception if the status code falls outside the range 200–299. Note that HttpClient can throw exceptions for other reasons-for example, if the request times out. +

+

Using Media-type formatters to deserialize

When Readasasync are called with no parameters, it uses a default set of media formatters to read the Res Ponse body. The default formatters support JSON, XML, and form-url-encoded data. +

Instead of using the default formatters, you can provide a list of formatters to the Readasync method, which is U Seful If you have a custom Media-type formatter:+

var formatters = new List<MediaTypeFormatter>() {    new MyCustomFormatter(),    new JsonMediaTypeFormatter(),    new XmlMediaTypeFormatter()};resp.Content.ReadAsAsync<IEnumerable<Product>>(formatters);

For more information, see Media formatters in ASP. NET Web API 2+

Sending a POST Request to Create a Resource

The following code sends a POST request that contains a Product instance in JSON format:+

static async Task<Uri> CreateProductAsync(Product product){    HttpResponseMessage response = await client.PostAsJsonAsync("api/products", product);    response.EnsureSuccessStatusCode();    // Return the URI of the created resource.    return response.Headers.Location;}

The Postasjsonasync method serializes an object to JSON and then sends the JSON payload in a POST request. If the request succeeds, it should return a 201 (Created) response, with the URL of the "the Created resources in the" location Header. +

+

Sending a PUT Request to Update a Resource

The following code sends a PUT request to update a product. +

static async Task UpdateProductAsync(Product product){    HttpResponseMessage response = await client.PutAsJsonAsync($"api/products/{product.Id}", product);    response.EnsureSuccessStatusCode();    // Deserialize the updated product from the response body.    product = await response.Content.ReadAsAsync<Product>();    return product;}

The Putasjsonasync method works like Postasjsonasync, except that it sends a PUT request instead of POST . +

+

Sending a delete Request to delete a Resource

The following code sends a delete request to delete a product. +

static async Task DeleteProductAsync(string id){    HttpResponseMessage response = await client.DeleteAsync($"api/products/{id}");    return response.StatusCode;}

Like GET, a DELETE request does not has a request body, so you don't need to specify JSON or XML format. +

Complete Code Example

Here was the complete code For this tutorial. The code is very-doesn ' t include much error handling, but it shows the basic CRUD operations using Http Client . +

Using system;using system.net;using system.net.http;using system.net.http.headers;using System.Threading.Tasks;        Namespace httpclientsample{public class Product {public string Id {get; set;}        public string Name {get; set;}        Public decimal price {get; set;}    public string Category {get; set;}        } class Program {static HttpClient client = new HttpClient (); static void Showproduct (product product) {Console.WriteLine ($ "Name: {product. Name}\tprice: {product. Price}\tcategory: {product.        Category} ");  } static Async task<uri> Createproductasync (product product) {Httpresponsemessage response = await client.            Postasjsonasync ("Api/products", product); Response.            Ensuresuccessstatuscode ();            Return URI of the created resource. return response.        Headers.location;    } static Async task<product> Getproductasync (string path) {        Product Product = NULL; Httpresponsemessage response = await client.            Getasync (path); if (response. Issuccessstatuscode) {Product = await response.            Content.readasasync<product> ();        } return product; } static Async task<product> Updateproductasync (product product) {Httpresponsemessage resp Onse = await client. Putasjsonasync ($ "api/products/{product.            ID} ", product); Response.            Ensuresuccessstatuscode ();            Deserialize the updated product from the response body. Product = await response.            Content.readasasync<product> ();        return product; } static Async task

Calling a Web API from a. NET Client (C #)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.