Integrating Demo Registration with External APIs in ASP.NET MVC C#

Introduction

In modern web applications, integrating external services can significantly enhance functionality and improve user experience. One such integration is with vehicle registration systems, where APIs enable admins to manage vehicle data seamlessly. In this article, we will explore the process of integrating a vehicle registration API into an ASP.NET MVC application. Specifically, we will focus on a method that adds a vehicle to an admin's system by communicating with an external service (base API) for tag registration.

The method we're discussing handles various tasks: preparing data, sending HTTP requests, processing responses, and managing errors. By the end of this guide, you'll have a solid understanding of how to use external APIs in your own web applications, ensuring smooth interactions between your system and third-party services.

Code

public async Task<ActionResult> Demoadminvehicle(GetDemoadmin model)
{
    // Create an instance of GetDemoadmin
    GetDemoadmin vehiInfo = new GetDemoadmin();

    // Set the properties of the model
    model.Id = Convert.ToInt32(Session["Id"]);
    model.MobileNumber = model.MobileNumber;
    model.name = model.name;
    model.no = model.no;

    // Base URL for the API
    string Baseurl = "https://api.base.id/v1/clint/demo";

    // Create request payload
    var requestData = new
    {
        consent = true,
        consentText = "I approve baseto capture",
        Number = model.no
    };

    // Serialize the object to JSON
    string jsonContent = JsonConvert.SerializeObject(requestData);

    // Create the HTTP web request
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Baseurl);
    request.Method = "POST";
    request.ContentType = "application/json";
    request.Accept = "application/json";
    request.Headers.Add("Authorization", "bse w6rCvk51oXJiKZgbhJeaHROpRe7AJf3T%2fmdiwjszkaU%2fnNgA%2f2");

    // Write JSON content to the request stream
    using (StreamWriter writer = new StreamWriter(await request.GetRequestStreamAsync()))
    {
        await writer.WriteAsync(jsonContent);
    }

    try
    {
        // Get the response from the server
        using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
        {
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                string responseData = await reader.ReadToEndAsync();
                vehiInfo = JsonConvert.DeserializeObject<GetResponseclientdash>(responseData);
                model.tagId = vehiInfo.tagId;

                Console.WriteLine("Response received successfully: " + responseData);
            }
        }
    }
    catch (WebException ex)
    {
        clsErrorLog.ErrorLog(
            "Exception: " + ex.ToString(),
            "Demoadminvehicle",
            "Demoadminvehicle"
        );
    }

    // Call provider method and return result as JSON
    var res = DemoProvider.Demoadminvehicle(model);
    return Json(res, JsonRequestBehavior.AllowGet);
}

The Demoadminvehiclemethod is responsible for registering a vehicle under a specific admin by making a request to the baseAPI, which handles vehicle services. This is achieved by accepting user input in the form of a GetDemoadmin object, preparing the request, and handling both the request and response.

Step-by-Step Breakdown

1. Model Preparation

The method begins by initializing a new instance of the GetDemoadmin class (vehiInfo) and sets the necessary properties from the input model (model). The properties include customer information such as NO, name, and VehicleNo. Additionally, the Id is fetched from the session (which may represent the location or specific context related to the admin).

2. Setting Up API Request Data

The next step is to configure the data that will be sent to the external API. A requestData anonymous object is created to include essential information, like the vehicle registration number and consent text. The consent is marked as true, indicating that the user agrees to the terms and conditions for data processing.

This request data is serialized into a JSON string using JsonConvert.SerializeObject will be the body of the HTTP POST request.

3. Setting Up the HTTP Web Request

With the data ready, the method sets up an HTTP POST request using the HttpWebRequest class. The request headers are configured to accept JSON responses, and an Authorization header is added for security purposes (Basic authentication).

The baseurl is the endpoint for the BureauID API, which provides fastag-related services.

4. Sending the Request

The method uses a StreamWriter to send the serialized JSON content to the API. This is done asynchronously using await writer.WriteAsync(jsonContent);.

5. Handling the API Response

Once the request is sent, the code awaits the response from the server. If successful, the response data is read and deserialized into a GetDemoadmin object. This object contains a tagId property, which is important to associate the vehicle with a unique identifier.

6. Error Handling

In the event of an error, such as network issues or API downtime, the method catches a WebException and logs the error using a custom logging class (clsErrorLog). This ensures that the application doesn't crash and that relevant error details are stored for debugging.

Output

Output image

Conclusion

The Demoadminvehicle method is a crucial part of the vehicle registration process for an admin, interacting with an external API for vehicle fastag services. It demonstrates how to handle HTTP requests and responses asynchronously, ensure data privacy with user consent, manage errors gracefully, and return useful information back to the client.