Home NewsX California Consumer Privacy Act (CCPA) Opt-Out Icon

California Consumer Privacy Act (CCPA) Opt-Out Icon

by info.odysseyx@gmail.com
0 comment 2 views


HttpClient is very flexible. You can send HTTP requests asynchronously, manage headers, handle authentication, and use cookies while maintaining granular control over request and response formats. Its reusable nature makes it an essential tool for making network requests in modern apps, whether connecting to web APIs, microservices, or handling file uploads and downloads.

What you get with HttpClient:

  • Performs all types of HTTP operations (GET, POST, PUT, DELETE, etc.).
  • Send and receive complex data such as JSON or multi-part form data.
  • Receive a response from a web service or API.
  • Handles asynchronous operations for efficient request management.

This article guides you how to create a simple console application in C# where the user can enter basic student details, roll number, name, age and upload the certificate. The certificate file can be in any format (pdf, doc, etc.). Send data to a web server using HttpClient.

Step 1: Create a new console application
Open a terminal or command prompt and run the following command to create a new console application.

dotnet new console -n StudentUploadApp

Go to your project directory.

cd StudentUploadApp

Step 2: Add required package
you are System.Net.Http Packages are usually included by default in the .NET SDK. If you need to install it, use:

dotnet add package System.Net.Http

Step 3: Write 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}");
            }
        }
    }
}

You need to change this URL.https://yourapi.com/upload” Use with the actual API endpoint where you need to send data. Make sure your server can handle multipart form data.

Step 4: Edit API controller
Create a new controller and replace its contents 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 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: Your API is now ready to accept POST requests. Run the API.

You can run the API using the following command:

dotnet run

Step 6: Finally, run the console application.

You will be asked to enter the student’s roll number, name, age and certificate file path. Check if the file exists in the specified path.

Now, when you run the console application and upload the student’s details along with the certificate file, the API will receive the data and save that file in the UploadedFiles directory of your API project. You can enhance the API by adding validation, error handling, and database integration as needed.

Finally, you will see a confirmation message in the console window as shown below.

hariomdubey_0-1727810302416.png

conclusion:

In this article, we explored the power of HttpClient by building a simple console application that uploads student details along with files to a web API. HttpClient is a powerful class in the .NET Framework that allows developers to easily perform HTTP tasks, including 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 settings, your application can easily handle complex file uploads and data transfers.





Source link

You may also like

Leave a Comment

Our Company

Welcome to OdysseyX, your one-stop destination for the latest news and opportunities across various domains.

Newsletter

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

Laest News

@2024 – All Right Reserved. Designed and Developed by OdysseyX