Overview
This prompt aims to guide software engineers in creating clean and maintainable C# code for adding parameters to an HttpRequestMessage. Developers specializing in .NET Core will benefit from the structured approach and best practices outlined.
Prompt Overview
Purpose: This guide demonstrates how to create an `HttpRequestMessage` in C# with parameters for clean and maintainable code.
Audience: This content is aimed at software engineers and developers familiar with C# and .NET Core.
Distinctive Feature: The code includes detailed comments and best practices for readability and maintainability.
Outcome: You will learn to add query parameters, headers, and content to an `HttpRequestMessage` effectively.
“`csharp
using System;
using System.Net.Http;
using System.Web;
public class HttpRequestExample
{
// Method to create an HttpRequestMessage with parameters
public HttpRequestMessage CreateRequest()
{
// Base URI for the API endpoint
var baseUri = new Uri(“https://api.example.com/resource”);
// Build the URI with query parameters
var builder = new UriBuilder(baseUri);
var query = HttpUtility.ParseQueryString(builder.Query);
query[“param1”] = “value1”; // Add first query parameter
query[“param2”] = “value2”; // Add second query parameter
builder.Query = query.ToString(); // Set the query string
// Create the HttpRequestMessage with GET method
var request = new HttpRequestMessage(HttpMethod.Get, builder.Uri);
request.Headers.Add(“Custom-Header”, “HeaderValue”); // Add a custom header
// Optionally, if needed, add content for POST or PUT requests
// request.Content = new StringContent(“{“key”:”value”}”, Encoding.UTF8, “application/json”);
return request; // Return the constructed request
}
}
“`
In this example, we create an `HttpRequestMessage`, add query parameters, and include custom headers while ensuring the code is clear and maintainable.
Quick Specs
- Media: Text
- Use case: Generation
- Industry: Development Tools & DevOps, Productivity & Workflow, Property Development
- Techniques: Role/Persona Prompting, Structured Output, Style Guide Adherence
- Models: Claude 3.5 Sonnet, Gemini 2.0 Flash, GPT-4o, Llama 3.1 70B
- Estimated time: 5-10 minutes
- Skill level: Intermediate
Variables to Fill
- ["param1"] – "param1"
- ["param2"] – "param2"
Example Variables Block
- ["param1"]: Example "param1"
- ["param2"]: Example "param2"
The Prompt
You are a software engineer specialized in .NET Core, tasked with demonstrating how to add parameters to an HttpRequestMessage in C#. Your response should focus on producing clean, maintainable, and high-quality code.
Please include detailed comments explaining each step and decision in the code to ensure clarity and ease of understanding for other developers.
# Steps
1. Briefly explain what HttpRequestMessage is and its typical use.
2. Show how to add query parameters to the request URL.
3. Demonstrate adding headers to the HttpRequestMessage.
4. Optionally, show how to add content parameters if appropriate (for POST or PUT requests).
5. Apply best practices for readability and maintainability, such as using helper methods or builders if needed.
6. Provide comments explaining the purpose of each part of the code.
# Output Format
– Provide well-formatted C# code snippets with inline comments.
– The code should be executable within a .NET Core environment and follow standard conventions.
# Examples
“`csharp
// Create an HttpRequestMessage and add query parameters and headers
var baseUri = new Uri(“https://api.example.com/resource”);
var builder = new UriBuilder(baseUri);
var query = HttpUtility.ParseQueryString(builder.Query);
query[“param1”] = “value1”;
query[“param2”] = “value2”;
builder.Query = query.ToString();
var request = new HttpRequestMessage(HttpMethod.Get, builder.Uri);
request.Headers.Add(“Custom-Header”, “HeaderValue”);
// Use the request in HttpClient
“`
# Notes
– Ensure the query parameters are URL-encoded properly.
– Avoid hardcoding strings; demonstrate the use of variables and constants where applicable.
– Mention any relevant namespaces or dependencies (like System.Net.Http or System.Web).
– Consider maintainability by avoiding code duplication and enhancing readability.
Screenshot Examples
How to Use This Prompt
- “`csharp
- using System
- using System
- Net
- Http
- using System
- Web
- namespace HttpRequestExample
- {
- class Program
- {
- static void Main(string[] args)
- {
- // Create the base URI for the API endpoint
- var baseUri = new Uri("https://api
- example
- com/resource")
- // Build the complete URI with query parameters
- var requestUri = BuildRequestUri(baseUri, "value1", "value2")
- // Create an HttpRequestMessage for a GET request
- var request = new HttpRequestMessage(HttpMethod
- Get, requestUri)
- // Add custom headers to the request
- AddCustomHeaders(request)
- // Use the request with HttpClient (not shown here)
- }
- ///
- /// Builds the request URI with query parameters
- ///
- /// The base URI of the API
- /// Value for the first query parameter
- /// Value for the second query parameter
- /// The complete URI with query parameters
- private static Uri BuildRequestUri(Uri baseUri, string param1Value, string param2Value)
- {
- // Use UriBuilder to modify the base URI
- var builder = new UriBuilder(baseUri)
- var query = HttpUtility
- ParseQueryString(builder
- Query)
- // Add query parameters
- query["param1"] = param1Value
- query["param2"] = param2Value
- // Set the modified query string back to the UriBuilder
- builder
- Query = query
- ToString()
- return builder
- Uri
- // Return the complete URI
- }
- ///
- /// Adds custom headers to the HttpRequestMessage
- ///
- /// The HttpRequestMessage to modify
- private static void AddCustomHeaders(HttpRequestMessage request)
- {
- // Add a custom header
- request
- Headers
- Add("Custom-Header", "HeaderValue")
- // Additional headers can be added here as needed
- }
- }
- }
- “`
- ### Explanation of Code:
- – Namespaces: The code uses `System
- Net
- Http` for HTTP requests and `System
- Web` for URL encoding
- – Main Method: Initializes the base URI and constructs the request URI with query parameters
- – BuildRequestUri Method: A helper method that constructs the full URI with query parameters, enhancing readability and maintainability
- – AddCustomHeaders Method: A separate method to add headers, promoting separation of concerns and reducing duplication
- – Comments: Each part of the code is documented to clarify its purpose and functionality
Tips for Best Results
- Understanding HttpRequestMessage: HttpRequestMessage is a class used to represent an HTTP request, encapsulating the request method, URL, headers, and content. It’s commonly used in .NET applications for making HTTP calls.
- Adding Query Parameters: Use UriBuilder to construct the request URL with query parameters. This ensures proper URL encoding and maintains readability.
- Setting Headers: Add custom headers to the HttpRequestMessage using the Headers property, which allows you to include additional metadata for the request.
- Content Parameters for POST Requests: For POST or PUT requests, use StringContent or similar classes to add body content, ensuring that the content type is set appropriately for the request.
FAQ
- What is HttpRequestMessage in C#?
HttpRequestMessage represents an HTTP request message, including method, headers, and content. - How do you add query parameters to HttpRequestMessage?
Use UriBuilder to construct the URL with query parameters, then create HttpRequestMessage. - How can headers be added to HttpRequestMessage?
Use the Headers property of HttpRequestMessage to add custom headers easily. - What are content parameters in HttpRequestMessage?
Content parameters are used in POST/PUT requests to send data in the request body.
Compliance and Best Practices
- Best Practice: Review AI output for accuracy and relevance before use.
- Privacy: Avoid sharing personal, financial, or confidential data in prompts.
- Platform Policy: Your use of AI tools must comply with their terms and your local laws.
Revision History
- Version 1.0 (February 2026): Initial release.


