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);
}

Join the conversation! Your thoughts help the community grow.