Web API: Client: HttpClient Message Handlers

 

 

原文地址: http://www.asp.net/web-api/overview/web-api-clients/httpclient-message-handlers

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net.Http;

using System.Text;

using System.Threading.Tasks;



namespace Test.WebAPI.Client

{

    public class CustomClientMessageHandler : DelegatingHandler 

    {

        private int count = 0;

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)

        {

            count++;

            Console.WriteLine(count);



            var response = await base.SendAsync(request, cancellationToken);



            if (!response.IsSuccessStatusCode)

            {

                Console.WriteLine("{0}\t{1}\t{2}", request.RequestUri, (int)response.StatusCode, response.Headers.Date);

            }



            return response;

        }

    }

}
CustomClientMessageHandler.cs
using System;

using System.Collections.Generic;

using System.Linq;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Text;

using System.Threading.Tasks;

using Test.EntityFramework.Models;



namespace Test.WebAPI.Client

{

    class Program

    {

        static void Main(string[] args)

        {



            // Custom client message handler

            TestCustomHanlder().Wait();





            Console.WriteLine("Exist...");



            Console.ReadLine();

        }



        public static async Task TestCustomHanlder()

        {

            using (HttpClient client = HttpClientFactory.Create(new CustomClientMessageHandler()))

            {

                client.BaseAddress = new Uri("http://localhost:55165/");

                client.DefaultRequestHeaders.Accept.Clear();

                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));





                HttpResponseMessage response = await client.GetAsync("api/test");  // Blocking call



                // Get

                if (response.IsSuccessStatusCode)

                {

                    // Parse the response body. Blocking!

                    var products = await response.Content.ReadAsAsync<IEnumerable<Test.EntityFramework.Models.Test>>();

                    foreach (var p in products)

                    {

                        Console.WriteLine("{0}\t{1};", p.ID, p.Title);

                    }

                }

                else

                {

                    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);

                }

            }

        }



    }

}
Program.cs

 

你可能感兴趣的:(httpclient)