European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC Hosting - HostForLIFE.eu :: How to Consume Web API in ASP.NET MVC Using HttpClient?

clock July 25, 2025 07:51 by author Peter

Do you need to retrieve data from a Web API when developing an ASP.NET MVC application? You don't need to search any farther! Using actual examples and recommended practices, this article will teach you how to use the HttpClient class in ASP.NET MVC to consume a Web API.

What You'll Learn

  • What is HttpClient in .NET?
  • How to make GET requests to an API.
  • Deserialize JSON response into objects.
  • Display API data in an MVC view.
  • Full working code example.

Why Use HttpClient?
The HttpClient class is a part of the System.Net.Http namespace and provides powerful capabilities to send HTTP requests and receive HTTP responses.

It supports

  • GET, POST, PUT, DELETE methods.
  • Asynchronous operations.
  • Custom headers and authentication.

Prerequisites

  • Visual Studio (2019 or newer recommended)
  • ASP.NET MVC project
  • A working Web API endpoint
  • NuGet package: Newtonsoft.Json

Steps to Calling Web API in ASP.NET MVC
Step 1. Create a Model
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
}

Step 2. Create Your Controller
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Mvc;
using Newtonsoft.Json;
using YourApp.Models;

public class HomeController : Controller
{
    string Baseurl = "https://yourapi.com/api/";

    public async Task<ActionResult> Index()
    {
        List<Employee> EmpInfo = new List<Employee>();

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(Baseurl);
            client.DefaultRequestHeaders.Clear();

            // Set header to accept JSON
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            // Call API
            HttpResponseMessage Res = await client.GetAsync("Employee/GetAllEmployees");

            // Check response
            if (Res.IsSuccessStatusCode)
            {
                var EmpResponse = Res.Content.ReadAsStringAsync().Result;

                EmpInfo = JsonConvert.DeserializeObject<List<Employee>>(EmpResponse);
            }
        }

        return View(EmpInfo);
    }
}


Step 3. Create the View (Index.cshtml)
@model IEnumerable<YourApp.Models.Employee>

<h2>Employee List</h2>

<table border="1">
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Department</th>
    </tr>

    @foreach (var emp in Model)
    {
        <tr>
            <td>@emp.Id</td>
            <td>@emp.Name</td>
            <td>@emp.Department</td>
        </tr>
    }
</table>

Notes and Best Practices

  • Don't instantiate HttpClient inside a loop or frequently. Consider reusing it with dependency injection.
  • Always check for IsSuccessStatusCode before using the response.
  • For APIs that require authentication (Bearer tokens, etc.), you can add headers:

client.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", token);

Install Newtonsoft.Json
Install-Package Newtonsoft.Json

Conclusion
This post taught you how to consume a Web API using the ASP.NET MVC HttpClient class. When front-end MVC has to retrieve data from external APIs or microservices, this method is frequently employed in enterprise apps.



ASP.NET MVC Hosting - HostForLIFE.eu :: Knowing ASP.NET MVC

clock July 15, 2025 10:27 by author Peter

ASP.NET MVC is a web application framework that helps developers create organized, scalable web applications. It is based on the Model-View-Controller (MVC) architectural pattern and is built on top of the Microsoft.NET platform.  Using C# and Razor syntax, it is frequently used to create dynamic webpages, dashboards, admin panels, and data-driven online applications.   In particular, it typically means:

  • ASP.NET MVC (for .NET Framework – Windows-only)
  • ASP.NET Core MVC (for .NET Core / .NET 5+ – cross-platform)

MVC, or Model–View–Controller, is a software design pattern that organizes an application into three interconnected components, each with a distinct responsibility:

  • Model: Manages the data and business logic. It’s like the brain of the application — storing, retrieving, and processing information.
  • View: Handles the presentation layer. Think of it as the face — what users see and interact with.
  • Controller: Acts as the coordinator. It receives user input, communicates with the model, and selects the appropriate view to display.

The Model-View-Controller (MVC) pattern is a core part of the .NET ecosystem. If you're learning about the .NET ecosystem, please read the full article at: Understanding the .NET Ecosystem. 

.NET MVC is a web development pattern and framework in .NET; it is not a language, but a structure used to build web apps efficiently.

ASP.NET Core MVC (part of .NET 8) is the current version of .NET MVC. It is used in all new development and supports modern features like Razor Pages, Minimal APIs, Blazor integration, dependency injection, and cloud/container readiness.

How does MVC work in a healthcare appointment portal?

Imagine a clinic where patients can

  • Register online
  • View available doctors
  • Book appointments
  • Track their visit history
  • Model: Represents entities like Patient, Doctor, Appointment, and Attendance. These classes hold data such as names, contact info, appointment times, and medical notes.
  • View: Displays forms for registration, appointment booking, and reports. It shows dynamic content like available slots and doctor profiles.
  • Controller: Handles user actions like submitting a booking form or requesting a report. It fetches data from the model and passes it to the view.

For example, when a patient books an appointment:

  • The Controller receives the request and validates it.
  • It uses the Model to store the appointment in the database.
  • Then it returns a View showing confirmation and upcoming appointments.

This setup allows doctors to manage their schedules, patients to interact with the system seamlessly, and admins to generate reports all within a clean, maintainable architecture.

Features of .NET MVC

  • Separation of Concerns: Keeps business logic (Model), UI (View), and input handling (Controller) separate, making code easier to manage and scale.
  • Testability: You can write unit tests for your business logic and controllers without involving the UI.
  • Clean URLs & SEO: Routing in MVC allows for readable, SEO-friendly URLs.
  • Full Control Over HTML: Unlike Web Forms, MVC gives you direct control over markup, which is great for responsive design and accessibility.
  • Extensibility: You can plug in custom filters, binders, and view engines to tailor the framework to your needs.
  • Parallel Development: Frontend and backend teams can work independently on Views and Controllers.

Conclusion
.NET MVC is a structured and efficient way to build dynamic, testable, and maintainable web applications using the Model-View-Controller (MVC) pattern in the .NET ecosystem. It separates application logic, data handling, and the user interface, making development more organized and scalable. In my learning, I’ve found that whether you're using ASP.NET MVC (legacy) or ASP.NET Core MVC (modern and recommended), understanding the MVC workflow is essential for building clean, scalable, and high-performance web applications.



ASP.NET MVC Hosting - HostForLIFE.eu :: Create a RESTful Student Information API using C#.NET and ASP.NET MVC

clock July 3, 2025 06:58 by author Peter

This article will demonstrate how to use ASP.NET MVC in C# to create a basic RESTful API. When a specific student ID is searched, this API will return student data (including name, date of birth, zip code, major department, and student ID). This beginner-friendly guide offers step-by-step instructions, code walkthroughs, and explanations to help you comprehend and complete the project.

Tools Required

  • Visual Studio 2019/2022 (Community Edition is free)
  • .NET Framework (4.7 or later)
  • Basic knowledge of C# syntax

Step 1. Create a New Web API Project

  • Open Visual Studio.
  • Click on File > New > Project.
  • Choose ASP.NET Web Application (.NET Framework).
  • Name your project StudentAPI and click OK.
  • Select the Web API template and click Create.

This sets up a basic project with preconfigured folders for Models, Controllers, and API routes.

Step 2. Create the Student Model
This model defines the structure of the student data.

File: Models/Student.cs
using System;

namespace StudentAPI.Models
{
    public class Student
    {
        public string StudentId { get; set; }     // Alphanumeric ID e.g. S1001
        public string Name { get; set; }          
        public DateTime DateOfBirth { get; set; } // e.g. 2001-06-15
        public string ZipCode { get; set; }       // e.g. 600001
        public string Major { get; set; }         // e.g. Computer Science
    }
}

Explanation

  • StudentId: Alphanumeric identifier for the student.
  • Name: Full name of the student.
  • DateOfBirth: The date of birth, stored as a DateTime object.
  • ZipCode: Postal code of the student’s residence.
  • Major: The department or field of study.

Step 3. Create the API Controller
The controller processes incoming HTTP requests and returns responses.

File: Controllers/StudentController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using StudentAPI.Models;

namespace StudentAPI.Controllers
{
public class StudentController : ApiController
{
    private static List<Student> students = new List<Student>
    {
        new Student
        {
            StudentId = "S1001",
            Name = "Carlos",
            DateOfBirth = new DateTime(2000, 3, 12),
            ZipCode = "600045",
            Major = "Mechanical Engineering"
        },
        new Student
        {
            StudentId = "S1002",
            Name = "Peter",
            DateOfBirth = new DateTime(2001, 7, 25),
            ZipCode = "641001",
            Major = "Electronics and Communication"
        },
        new Student
        {
            StudentId = "S1003",
            Name = "Scott",
            DateOfBirth = new DateTime(1999, 12, 30),
            ZipCode = "500081",
            Major = "Computer Science"
        }
    };

    // GET api/student/{id}
    public IHttpActionResult GetStudentById(string id)
    {
        var student = students.FirstOrDefault(
            s => s.StudentId.Equals(id, StringComparison.OrdinalIgnoreCase));

        if (student == null)
        {
            return NotFound();
        }

        return Ok(student);
    }
}
}

Explanation

  • We use an in-memory List<Student> to simulate a database.
  • The method GetStudentById accepts an ID as input.
  • It searches for the student in the list using LINQ.
  • If found, it returns the student data in JSON format.
  • If not found, it returns a 404 (Not Found) HTTP response.

Step 4. Configure Web API Routing
Ensure your app correctly maps incoming API requests.

File: App_Start/WebApiConfig.cs
using System.Web.Http;

namespace StudentAPI
{
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Enable attribute routing
        config.MapHttpAttributeRoutes();

        // Define default route
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
}


Explanation

  • Enables attribute routing.
  • Sets a default route pattern: api/{controller}/{id}.
  • This means a call to api/student/S1001 will map to StudentController.

Step 5. Run and Test Your API

  • Press F5 or click Start Debugging in Visual Studio.
  • The browser will open. Change the URL to:

http://localhost:1234/api/student/S1002

(Replace the port 1234 with your actual port number.)

Example Output
{
  "StudentId": "S1002",
  "Name": "peter",
  "DateOfBirth": "2000-08-25 T00:00:00",
  "ZipCode": "641001",
  "Major": "Electronics and Communication"
}

Happy Learning!



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in