Uploading Files and Sending data using HttpClient: A Simple Guide
HttpClient stands out for its flexibility. It can send HTTP requests asynchronously, manage headers, handle authentication, and work with cookies, all while giving you detailed control over request and response formats. Its reusable nature makes it an essential tool for making network requests in modern apps, whether you’re connecting to web APIs, microservices, or handling file uploads and downloads.
What you can achieve with HttpClient:
Perform all types of HTTP operations (GET, POST, PUT, DELETE, etc.).
Send and receive complex data such as JSON or multipart form data.
Receiving responses from web services or APIs.
Handling asynchronous operations for efficient request management.
In this article, we will walk through creating a simple console application in C# that allows users to input basic student details, Roll Number, Name, Age and upload a certificate. The certificate file can be in any format (pdf, doc etc.). We will use HttpClient to send the data to a web server.
Step 1: Create a new Console Application
Open your terminal or command prompt and run the following command to create a new console application:
dotnet new console -n StudentUploadApp
Navigate into the project directory:
cd StudentUploadApp
Step 2: Add Required Packages
You will need the System.Net.Http package, which is typically included by default in .NET SDK. If you need to install it, use:
dotnet add package System.Net.Http
Step 3: Write the Application Code
Open the Program.cs file and replace the existing code with the following:
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
class Program
{
private static readonly HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
Console.Write(“Enter Student Roll Number: “);
string rollNumber = Console.ReadLine();
Console.Write(“Enter Student Name: “);
string studentName = Console.ReadLine();
Console.Write(“Enter Student Age: “);
string studentAge = Console.ReadLine();
Console.Write(“Enter path to Birth Certificate PDF: “);
string pdfPath = Console.ReadLine();
if (File.Exists(pdfPath))
{
await UploadStudentData(rollNumber, studentName, studentAge, pdfPath);
}
else
{
Console.WriteLine(“File not found. Please check the path and try again.”);
}
}
private static async Task UploadStudentData(string rollNumber, string name, string age, string pdfPath)
{
using (var form = new MultipartFormDataContent())
{
form.Add(new StringContent(rollNumber), “rollNumber”);
form.Add(new StringContent(name), “name”);
form.Add(new StringContent(age), “age”);
var pdfContent = new ByteArrayContent(await File.ReadAllBytesAsync(pdfPath));
pdfContent.Headers.ContentType = MediaTypeHeaderValue.Parse(“application/pdf”);
form.Add(pdfContent, “birthCertificate”, Path.GetFileName(pdfPath));
// Replace with your actual API endpoint
var response = await client.PostAsync(“https://yourapi.com/upload”, form);
if (response.IsSuccessStatusCode)
{
Console.WriteLine(“Student data uploaded successfully!”);
}
else
{
Console.WriteLine($”Failed to upload data: {response.StatusCode}”);
}
}
}
}
Please note that you need to replace this URL “https://yourapi.com/upload” with your actual API endpoint where the data should be sent. Ensure the server can handle multipart form data.
Step 4: Modify your API Controller
Create a new controller and replace its content with the following code:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Threading.Tasks;
namespace StudentUploadApi.Controllers
{
[ApiController]
[Route(“api/[controller]”)]
public class StudentController : ControllerBase
{
[HttpPost(“upload”)]
public async Task<IActionResult> UploadStudentData(
[FromForm] string rollNumber,
[FromForm] string name,
[FromForm] string age,
[FromForm] IFormFile birthCertificate)
{
if (birthCertificate == null || birthCertificate.Length == 0)
{
return BadRequest(“No file uploaded.”);
}
var filePath = Path.Combine(“UploadedFiles”, birthCertificate.FileName);
// Ensure the directory exists
Directory.CreateDirectory(“UploadedFiles”);
// Save the uploaded file to the specified path
using (var stream = new FileStream(filePath, FileMode.Create))
{
await birthCertificate.CopyToAsync(stream);
}
// Here, you can add logic to save the student data to a database or perform other operations
return Ok(new { RollNumber = rollNumber, Name = name, Age = age, FilePath = filePath });
}
}
}
Step 5: Now, your API is ready to accept POST requests. Run the API.
You can run your API with the following command:
dotnet run
Step 6: Finally, run your console application.
You will be prompted to enter the student’s Roll Number, Name, Age, and the path to their certificate file. Make sure the file exists at the specified path.
Now, when you run your console application and upload a student’s details along with the certificate file, the API will receive the data and save the file to UploadedFiles directory in your API project. You can enhance the API by adding validations, error handling, and database integration as needed.
Finally, you should see a confirmation message in the console window as below.
Conclusion:
In this article, we explored the power of HttpClient by building a simple console application that uploads student details along with a file to a web API. HttpClient is a powerful class in the .NET framework enabling developers to easily perform HTTP operations such as sending and receiving data, managing headers, and handling multipart form data. Whether you’re building client-side apps or interacting with external APIs, HttpClient simplifies communication. With the right setup, you can handle complex file uploads and data transmissions effortlessly in your applications.
Microsoft Tech Community – Latest Blogs –Read More