3.51Adding Response Status Code Handlers

Created on Aug 17, 2026~3 min read

When sending an HTTP request and receiving a response, we often need to perform specific operations based on different response status codes. To meet this need, HttpRequestBuilder provides the WithStatusCodeHandler method, which allows us to configure callback handling logic for specific status codes.

The following is an example of how to use the WithStatusCodeHandler method:

cs
HttpRequestBuilder.Get("https://furion.net/")    // Configure a callback handler for status code 200    .WithStatusCodeHandler(200, async (responseMessage, cancellationToken) =>    {        Console.WriteLine("Status code handler invoked");    })    // Configure a callback handler for status code 200    .WithStatusCodeHandler(HttpStatusCode.OK, async (responseMessage, cancellationToken) =>    {        Console.WriteLine("Status code handler invoked");    })    // Configure a callback handler for status codes in the range 200 ~ 299 (inclusive)    .WithStatusCodeHandler("200-299", async (responseMessage, cancellationToken) => // Equivalent to "200~299"    {        Console.WriteLine("Status code handler invoked");    })    // Supports comparison operators such as: >=200, <=300, <100, =100, >100    .WithStatusCodeHandler(">=200", async (responseMessage, cancellationToken) =>    {        Console.WriteLine("Status code handler invoked");    })    // Configure a unified callback handler for status codes 200, 204, and 500    .WithStatusCodeHandler([200, 204, 500], async (responseMessage, cancellationToken) =>    {        Console.WriteLine("Status code handler invoked");    })    // Configure a unified callback handler for all status codes    .WithAnyStatusCodeHandler(async (responseMessage, cancellationToken) =>    {        Console.WriteLine("Status code handler invoked");    })    // Configure a unified callback handler for status codes 200~299 (successful requests)    .WithSuccessStatusCodeHandler(async (responseMessage, cancellationToken) =>    {        Console.WriteLine("Status code handler invoked");    })    // Supports multiple status code representations, including the HttpStatusCode enum, string status codes, status code ranges, comparison operators, and wildcards    .WithStatusCodeHandler([200, "204", HttpStatusCode.InternalServerError, "200-299", ">=200", "*"], async (responseMessage, cancellationToken) =>    {        Console.WriteLine("Status code handler invoked");    });

With the WithStatusCodeHandler method, we can flexibly perform different operations based on the response status code, thereby enhancing the ability to handle HTTP requests and responses.