3.63Conditional Configuration Builder

Created on Aug 17, 2026~2 min read

When building a builder instance for an HTTP remote request, you often need to dynamically configure request parameters based on different conditions. For example, when the user performs a search operation, the ?search=keyword query parameter should be added to the request; otherwise, it need not be added.

For such scenarios, HttpRequestBuilder provides the When method to execute the corresponding configuration operation based on a specified condition. This method supports chained calls, making the code cleaner and clearer.

cs
HttpRequestBuilder.Post("https://furion.net")    .When(!string.IsNullOrEmpty(token), b => b.AddBearerAuthentication(token))    .When(!string.IsNullOrEmpty(keyword), b => b.WithQueryParameter("search", keyword));

Explanation of the sample code:

  • When token is not empty or null, Bearer authentication is automatically added.
  • When keyword is not empty or null, the search query parameter is added to the request.

This approach can be flexibly applied to various conditional judgment scenarios, improving the maintainability and readability of the code.