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 Use Cookie In ASP.NET Core Application?

clock September 12, 2025 08:02 by author Peter

Anyone interested in learning how to use the Asp.net core MVC application to save data in browser cookies should read this post. You can use the Asp.net Core MVC web application to develop a sample web application if you wish to put it into practice.

Let's begin.

In essence, a cookie is a tiny bit of information sent to the user's web browser by the server. It might be saved by the browser and sent back to the same server with a subsequent request. Usually, the browser uses it to determine whether two requests originated from the same browser.

Types of cookie 
Persistent cookie

A cookie that has not to have expired time which is called a persistent cookie 

Non-Persistent cookie

Cookie which has expired time is called a Non-persistent cookie 

Adding cookie to the browser
First, add methods inside the Home controller. I have created an action method as CreateCookie and I have added key as DemoCookie. After that I have stored string value as Yogesh so we can store this value in the client browser 
public IActionResult CreateCookie() {
    string key = "DemoCookie:;
    string value = Yogesh;
    cookieOptions obj = new CookieOptions();
    obj.Expires = DateTime.Now.AddDays(7);
    Response.Cookie.Append(key, value, options);
    return view();
}


To see the cookie which is added in the browser I am using Google Chrome.

Now we will see how to retrieve data from cookies, here I have created Action Method ReadData that is used to retrieve data from cookies.
public IActionResult Read Data() {
    string key = "DemoCookie";
    var CookieValue = Request.Cookies[key];
    return View();
}

Now we will see how to delete data that is stored in cookies, here I have created the Action method Delete to perform the Delete operation on the cookie.

public IActionResult Delete() {
    string key = "DemoCookie";
    string value = DateTime.Now.ToString();
    CookieOptions options = new CookieOptions();
    options.Expires = DateTime.Now.AddDays(-1);
    Response.Cookies.Append(key, value, options);
    return View();
}

Summary 
In this article, we have seen how to store data into cookies and retrieve and delete data from cookies. Hope you guys like it. Happy Coding!



ASP.NET MVC Hosting - HostForLIFE.eu :: A Comprehensive Guide on Partial View vs. ViewComponent in ASP.NET MVC/Core

clock September 3, 2025 07:12 by author Peter

Both appear to be comparable at first glance. They enable us to reuse user interface elements on other sites. However, they differ greatly under the hood. The distinctions, applications, performance factors, and when to pick one over the other will all be covered in this article.

What is a Partial View?

  • A Partial View is a Razor view (.cshtml) file that can be reused inside other views.
  • It is essentially a fragment of HTML + Razor that does not have its own controller logic.

Think of it like a shared template. If you’ve worked with ASP.NET WebForms before, you can compare it to a UserControl (.ascx).
Example

_LoginPartial.cshtml
@if (User.Identity.IsAuthenticated)
{
    <p>Welcome, @User.Identity.Name</p>
    <a href="/Account/Logout">Logout</a>
}
else
{
    <a href="/Account/Login">Login</a>
}

You can include it in your main view as:
@Html.Partial("_LoginPartial")

or asynchronously:

@await Html.PartialAsync("_LoginPartial")
Key Point: A Partial View does not have its own logic. It depends on the data passed from the parent view’s controller.

What is a ViewComponent?
A ViewComponent is like a mini-controller.
It combines C# logic + a Razor view into a self-contained unit.

It allows you to encapsulate business logic and rendering in one place, making it perfect for widgets that require their own data fetching.

Example
ViewComponents/CartSummaryViewComponent.cs
public class CartSummaryViewComponent : ViewComponent
{
    private readonly ICartService _cartService;

    public CartSummaryViewComponent(ICartService cartService)
    {
        _cartService = cartService;
    }

    public IViewComponentResult Invoke()
    {
        var cart = _cartService.GetCart(User.Identity.Name);
        return View(cart);
    }
}


The Razor view (Views/Shared/Components/CartSummary/Default.cshtml):
<div class="cart-summary">
    <p>Items in cart: @Model.Items.Count</p>
    <p>Total: @Model.TotalPrice.ToString("C")</p>
</div>

Usage in your main view:
@await Component.InvokeAsync("CartSummary")

Key Point: A ViewComponent has its own logic and data source. It does not rely on the parent controller’s model.

Key Differences Between Partial View and ViewComponent

FeaturePartial ViewViewComponent
Definition Reusable HTML + Razor fragment Mini controller + view
Logic Handling No (uses parent’s controller/model) Yes (has its own C# logic class)
Data Binding Uses parent ViewData, ViewBag, Model Accepts parameters, independent model
Execution Rendered inside parent’s lifecycle Executes independently like a child action
Reusability Best for static/common layouts Best for dynamic, data-driven widgets
Performance Lightweight Slightly heavier but cleaner separation
Examples Header, Footer, Menu, Static widgets Notifications, Cart summary, Latest posts

When to Use Partial View?

Use a Partial View when:

  • You only need reusable HTML markup.
  • Data comes from the parent controller.
  • Example scenarios:
  • Website header and footer
  • Navigation menus
  • Shared static templates like the Terms & Conditions section

Code Example

@Html.Partial("_Header")
@Html.Partial("_Footer")


When to Use ViewComponent?

Use a ViewComponent when:

  • You need business logic + view rendering together.
  • Data comes from a different source than the parent view.
  • You want testability (since ViewComponents can be unit tested).
  • Example scenarios:
    • Shopping cart summary
    • Latest blog posts widget
    • Notification panel
    • User profile box

Code Example
@await Component.InvokeAsync("LatestPosts", new { count = 5 })

Performance Considerations

  • Partial View is faster for simple static rendering because it does not invoke additional logic.
  • ViewComponent is slightly heavier, but it provides better separation of concerns and testability.
  • In real-world projects, mixing both approaches works best.

Conclusion
ASP.NET MVC/Core offers two strong tools for creating modular, maintainable applications: Partial Views and ViewComponents.

  • For basic, static UI fragments, use partial views.
  • For reusable, logic-driven user interface elements, use ViewComponents.

You may improve the scalability, maintainability, and cleanliness of your application by selecting the appropriate strategy for each situation.



ASP.NET MVC Hosting - HostForLIFE.eu :: ASP.NET Core MVC Applications' Data Security

clock August 29, 2025 08:00 by author Peter

Data security is one of the most critical concerns when building ASP.NET Core MVC applications. From user credentials to financial transactions, sensitive data must be protected against threats such as SQL Injection, Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), and unauthorized access. In this article, we’ll explore end-to-end data security practices in ASP.NET Core MVC applications with real-world code examples and best practices that you can apply directly in your projects.

1. Enforce HTTPS Everywhere
Always use TLS/SSL to ensure secure communication between the client and server.

Program.cs
builder.Services.AddHttpsRedirection(options =>
{
    options.HttpsPort = 443;
});

var app = builder.Build();
app.UseHttpsRedirection();

Never transmit sensitive data over plain HTTP.

2. Secure Authentication and Authorization

ASP.NET Core provides Identity for authentication, or you can use external providers like Google, Azure AD, or JWT tokens.

Authorization Policy Example
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
});


Controller Usage
[Authorize(Policy = "AdminOnly")]
public IActionResult AdminDashboard()
{
    return View();
}


Always store passwords using hashing algorithms. ASP.NET Core Identity uses PBKDF2 by default.

3. Protect Sensitive Configuration Data

Never hardcode credentials or API keys in your appsettings.json .
Development → Use User Secrets
dotnet user-secrets set "DbPassword" "SuperSecurePassword123!"

Production → Use Azure Key Vault

builder.Configuration.AddAzureKeyVault(
new Uri("https://myvault.vault.azure.net/"),
new DefaultAzureCredential());


This keeps sensitive data out of source control.

4. Encrypt Sensitive Data at Rest

If your app handles PII (Personally Identifiable Information) such as SSN, credit card numbers, or health records, use encryption.

AES Encryption Helper
public static class EncryptionHelper
{
    private static readonly string Key = "YourEncryptionKey1234"; // Store securely

    public static string Encrypt(string plainText)
    {
        using var aes = Aes.Create();
        var encryptor = aes.CreateEncryptor(Encoding.UTF8.GetBytes(Key), aes.IV);
        using var ms = new MemoryStream();
        ms.Write(aes.IV, 0, aes.IV.Length);
        using var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
        using (var sw = new StreamWriter(cs)) sw.Write(plainText);
        return Convert.ToBase64String(ms.ToArray());
    }
}

Store only encrypted values in your database.

5. Validate Input & Prevent SQL Injection

ASP.NET Core Entity Framework Core automatically parameterizes queries, protecting against SQL injection.

Wrong (Vulnerable)
var user = _context.Users.FromSqlRaw(
$"SELECT * FROM Users WHERE Username = '{username}'").FirstOrDefault();

Correct (Safe)
var user = await _context.Users
.FirstOrDefaultAsync(u => u.Username == username);

Always use LINQ queries or parameterized SQL.

6. Prevent Cross-Site Scripting (XSS)

ASP.NET Core Razor automatically encodes output.

<p>@Model.Name</p> <!-- Safe -->

If you must allow HTML.
@Html.Raw(Model.Description) // Use carefully

Use libraries like Ganss.XSS to sanitize user-generated content.

7. Enable CSRF Protection

ASP.NET Core MVC provides built-in CSRF protection with anti-forgery tokens.

Controller
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult SaveData(MyModel model)
{
    // Save logic
    return RedirectToAction("Index");
}


View
<form asp-action="SaveData" method="post">
    @Html.AntiForgeryToken()
    <button type="submit">Submit</button>
</form>


This prevents malicious sites from posting forms on behalf of logged-in users.

8. Secure Cookies & Sessions

Always configure cookies with HttpOnly and Secure flags.

builder.Services.ConfigureApplicationCookie(options =>
{
    options.Cookie.HttpOnly = true;
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    options.SlidingExpiration = true;
});

This prevents cookie theft via JavaScript.

9. Secure File Uploads

If your app allows file uploads.

  • Validate file types & sizes.
  • Store files outside. wwwroot
  • Rename files to avoid execution.

Example validation
if (!file.ContentType.StartsWith("image/"))
throw new Exception("Invalid file type!");


10. Enable Security Headers
Add middleware to strengthen browser protections.
app.Use(async (context, next) =>
{
    context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
    context.Response.Headers.Add("X-Frame-Options", "DENY");
    context.Response.Headers.Add("X-XSS-Protection", "1; mode=block");
    await next();
});


Use NWebSec for advanced headers.

11. Logging & Monitoring

  • Use Serilog/NLog for structured logging.
  • Monitor failed login attempts.
  • Never log sensitive data (passwords, tokens, credit cards).

12. Prevent Denial of Service (DoS) Attacks
ASP.NET Core 7 and later support built-in rate limiting.
builder.Services.AddRateLimiter(_ => _
.AddFixedWindowLimiter("fixed", options =>
{
    options.Window = TimeSpan.FromSeconds(10);
    options.PermitLimit = 5;
}));


Deploy a WAF (Web Application Firewall) in production.

Conclusion

Securing data in ASP.NET Core MVC applications requires a multi-layered approach.

Enforce HTTPS

  • Secure authentication & authorization
  • Protect configuration & secrets
  • Encrypt sensitive data
  • Prevent SQL Injection, XSS, and CSRF.
  • Harden cookies, sessions, file uploads, and headers
  • Enable logging, monitoring, and rate limiting

By following these practices, you’ll ensure your application complies with modern security standards and is resilient against common web vulnerabilities.



ASP.NET MVC Hosting - HostForLIFE.eu :: PDF Generation in ASP.NET Core MVC using Puppeteer Sharp

clock August 22, 2025 09:06 by author Peter

In today’s digital world, internet activities are a vital part of our everyday life. Web-based applications are becoming more and more necessary as a result of this. The capacity to create PDFs from HTML is a common need of many web-based programs. Online ticketing, certifications, online purchase invoices, and many more are examples of everyday use cases.


Although utilities like DinkToPdf and iTextSharp can convert HTML to PDF, they frequently have trouble rendering in current CSS and JavaScript. This is Puppeteer Sharp's strong suit.

Puppeteer Sharp provides browser-quality PDFs, supports dynamic content, and integrates seamlessly into .NET apps, making it a significant improvement over traditional PDF generation libraries for web content.

Puppeteer Sharp is a .NET port of Google’s Puppeteer, a Node.js library for controlling Chrome or Chromium. It allows developers to.

  • Render HTML just like a browser would.
  • Apply advanced CSS styling.
  • Run JavaScript before capturing.
  • Export the rendered page to a PDF.

Benefits of using Puppeteer Sharp

  • Accurate Rendering: It uses the Chromium browser engine to maintain the accuracy of rendering.
  • Modern CSS and JavaScript Support: It can handle dynamic pages and animations.
  • Custom Layouts: Paper sizes, margins, headers and footers can be customized.
  • Automation Ready: It can be used in background tasks.


Installing Puppeteer Sharp

  • Using Visual Studio (NuGet Package Manager UI)
    • Right-click on your project in Solution Explorer.
    • Select Manage NuGet Packages for Solution.
    • Go to the Browse tab.
    • Search for PuppeteerSharp.
    • Select the latest stable version.
    • Click Install.

Using Package Manager Console: Open Tools > NuGet Package Manager > Package Manager Console, then run.

Install-Package PuppeteerSharp

Using .NET CLI: If you prefer the terminal/command line, run.

dotnet add package PuppeteerSharp

Generating a PDF from a Web page
Generate Invoice Example.
    [HttpPost]
    [Route("generate-invoice-pdf")]
    public async Task<IActionResult> GenerateInvoicePdf()
    {
        // Downloads Chromium if it's not already available
        await new BrowserFetcher().DownloadAsync();

        // Launch headless Chromium
        await using var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });

        // Open a new page
        await using var page = await browser.NewPageAsync();

        // Navigate to a URL (can also be a local MVC view)
        var url = $"{Request.Scheme}://{Request.Host}/pdf";
        await page.GoToAsync(url, WaitUntilNavigation.Networkidle0);

        // Generate PDF
        var pdfBytes = await page.PdfDataAsync(new PdfOptions
        {
            Format = PaperFormat.A4,
            PrintBackground = true,
            MarginOptions = new MarginOptions
            {
                Top = "20px",
                Bottom = "20px",
                Left = "20px",
                Right = "20px"
            }
        });

        // Close the browser
        await browser.CloseAsync();

        // Returns downloadable file
        var fileName = $"PDF_{DateTime.Now:yyyyMMdd_HHmm}.pdf";
        return File(pdfBytes, "application/pdf", fileName);
    }


Generate an External Web Page as a PDF.
[HttpPost]
[Route("generate-html-pdf")]
public async Task<IActionResult> GenerateHtmlPdf()
{
    // Downloads Chromium if it's not already available
    await new BrowserFetcher().DownloadAsync();

    // Launch headless Chromium
    await using var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });

    // Open a new page
    await using var page = await browser.NewPageAsync();

    // Navigate to a URL (can also be a local MVC view)
    var url = "https://www.google.com/";
    await page.GoToAsync(url, WaitUntilNavigation.Networkidle0);

    // Generate PDF
    var pdfBytes = await page.PdfDataAsync(new PdfOptions
    {
        Format = PaperFormat.A4,
        PrintBackground = true,
        MarginOptions = new MarginOptions
        {
            Top = "20px",
            Bottom = "20px",
            Left = "20px",
            Right = "20px"
        }
    });

    // Close the browser
    await browser.CloseAsync();

    // Returns downloadable file
    var fileName = $"PDF_{DateTime.Now:yyyyMMdd_HHmm}.pdf";
    return File(pdfBytes, "application/pdf", fileName);
}

Razor View.
<h2>Generate PDF using Puppeteer Sharp</h2>

<div style="display: flex; justify-content: space-between; align-items: center; width: 33%; margin: 50px auto 0 auto;">
    <form asp-controller="Pdf" asp-action="GenerateInvoicePdf" method="post" style="margin: 0;">
        <button type="submit" class="btn btn-primary">Download Invoice PDF</button>
    </form>
    <form asp-controller="Pdf" asp-action="GenerateHtmlPdf" method="post" style="margin: 0;">
        <button type="submit" class="btn btn-primary">Download Web PDF</button>
    </form>
</div>


How does it work?

  • First BrowserFetcher downloads a compatible chromium browser if needed.
  • The LaunchAsync method starts a headless instance of Chromium
  • NewPageAsync opens a new tab in Chromium. If Headless is set to false then you will see the browser's window with tab.
  • GoToAsync navigates to the target URL
  • PDFDataAsync captures the page as a PDF in memory.
  • The PDF is returned as a downloadable file to the client

Additional Tips
For the first time the PDF generation is slow and it’s the common issue with Puppeteer Sharp. To solve this problem, pre-download Chromium. This way, you can avoid first-request delays.

// Pre-download Chromium at startup
var fetcher = new BrowserFetcher();
await fetcher.DownloadAsync();

Suppose you add the above lines of code to your Program.cs, Chromium is downloaded during the application initialization for the first time.

Conclusion

Puppeteer Sharp is one of the powerful tools for PDF generation with modern web compatibility. It brings the flexibility of Chromium automation into the .NET ecosystem. Whether you are adding a PDF export feature or generating screenshots for preview, Puppeteer Sharp is a robust choice in .NET. With just a few lines of code, you can easily automate complex HTML to PDF. Note. Project source code can be downloaded from GitHub



ASP.NET MVC Hosting - HostForLIFE.eu :: Email Notification Using Web API 2 in ASP.NET MVC 5

clock August 7, 2025 08:53 by author Peter

In this post, we'll build the Web API, use MVC 5 to access it, and use Web API 2 to send emails.


Let's begin gradually:

  • Work with a web application by creating an ASP.NET web application.
  • Including a model
  • Including a controller
  • Including a Helper class
  • Using JavaScript and JQuery to Call the Web Api (test web API)
  • To call the API and send an email notification, use the Rest client (Install Fiddler).
Create the project
Start Visual Studio 2013/2015 and from the File menu, select New, then Project.
Select the ASP.NET Web Application project template. Name the project Email Notification and click OK.

Select a template Web API.

Add a model class
A model is an object that represents the data in your application. In this case, the only model is a TeamA item.

Add a class file “TeamA.cs”.

Replace the generated code with:
    namespace EmailNotification.Models  
    {  
        public class TeamA  
        {  
            public int Id  
            {  
                get;  
                set;  
            }  
            public string Name  
            {  
                get;  
                set;  
            }  
            public string Type  
            {  
                get;  
                set;  
            }  
            public decimal Price  
            {  
                get;  
                set;  
            }  
        }  
    }  


Add a controller

In the Add Scaffold wizard, select the Web API 2 Empty Controller: Name it EmailNotifier.

In the Add Controller dialog, name the controller "EmailNotifierController " and click Add.

Replace code with the following controller.
    public class EmailNotifierController: ApiController  
    {  
        TeamGroupA[] teamA = new TeamGroupA[]  
        {  
            new TeamGroupA  
            {  
                Id = 1, Name = "zing", Type = "Cricket", Price = 1  
            },  
            new TeamGroupA  
            {  
                Id = 2, Name = "Yo-yo", Type = "Football", Price = 3.75 M  
            },  
            new TeamGroupA  
            {  
                Id = 3, Name = "soft", Type = "Software", Price = 16.99 M  
            }  
        };  
        // Run the application  
        public IEnumerable < TeamGroupA > GetAllTeams()  
        {  
            return teamA;  
        }  
    }  


To keep the example simple, TeamGroupA has stored in a fixed array inside the controller class. But, in a real application, you would get it from the Data access layer or use some other external data source.

The controller defines two methods that return products:
The GetAllTeams method returns the entire list of products as an IEnumerable<TeamGroupA> type.

As we are working with Web API it may contain one or more methods.

Now add new model for AdpaterResponsebase for another API method as SendEmailNotification.cs.

AdapterResponseBase.cs

Replace model code with the following code:
    using System;  
    using System.Collections.Generic;  
    namespace EmailNotification.Models  
    {  
        public class ResponseBase  
        {}  
        public class RequestBase  
        {}  
        public class RequestBase < T > : RequestBase  
        {  
            public RequestBase()  
            {}  
            public RequestBase(T data)  
            {  
                Data = data;  
            }  
            public T Data  
            {  
                get;  
                set;  
            }  
        }  
    }  


Add new Helper class file EMailHelper.cs to folder named Helpers.

    using System;  
    namespace EmailNotofication.Models  
    {  
        public class EmailInput  
        {  
            public string UserName  
            {  
                get;  
                set;  
            }  
            public string EmailId  
            {  
                get;  
                set;  
            }  
        }  
    }  

Now we will start with UI part.

Calling the Web API with Javascript and jQuery

Here we will add an HTML page that uses AJAX to call the web API. We'll use jQuery to make the AJAX calls and also to update the page with the results.
In Solution Explorer, right-click the project and select Add, then select New Item.

In the Add New Item dialog, select the Web node under Visual C#, and then select the HTML Page item. Name the page "index.html".


Replace everything in this file with the following:
    <!DOCTYPE html>  
    <html xmlns="http://www.w3.org/1999/xhtml">  
      
    <head>  
        <title>Notification App</title>  
    </head>  
      
    <body>  
        <div>  
            <h2>All Teams</h2>  
            <ul id="teams" /> </div>  
        <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>  
        <script>  
            var uri = 'api/EmailNotifier/GetAllTeams';  
            $(document).ready(function()  
            {  
                // Send an AJAX request  
                $.getJSON(uri).done(function(data)  
                {  
                    // On success, 'data' contains a list of teams.  
                    $.each(data, function(key, item)  
                    {  
                        // Add a list item for the teams.  
                        $('<li>',  
                        {  
                            text: formatItem(item)  
                        }).appendTo($('#teams'));  
                    });  
                });  
            });  
      
            function formatItem(item)  
            {  
                return item.Name + ': $' + item.Price;  
            }  
        </script>  
    </body>  
      
    </html>  


Getting a List of Teams
To get a list of teams, send an HTTP GET request to "/api/GetAllTeams".

Set index.html as start page:

Run the project,
Yippee! Here we got success for calling Web API using Ajax. Now let’s add method for Email Notification.

We will call SendEmailNotification API using RestClient.

Add the following method to controller:
    [HttpPost]  
    public async Task < IHttpActionResult > SendEmailNotification(EmailInput data)  
    {  
        ResponseBase updateResponse = new ResponseBase();  
        var updateRequest = new RequestBase < EmailInput > (data);  
        try  
        {  
            EMailHelper mailHelper = new EMailHelper(EMailHelper.EMAIL_SENDER, EMailHelper.EMAIL_CREDENTIALS, EMailHelper.SMTP_CLIENT);  
            var emailBody = String.Format(EMailHelper.EMAIL_BODY);  
            if(mailHelper.SendEMail(data.EmailId, EMailHelper.EMAIL_SUBJECT, emailBody))  
            {  
                //   
            }  
        }  
        catch(Exception ex)  
        {}  
        return Ok(updateResponse);  
    }  

You need to add extension for RestClient to your chrome browser to call API. Pass the parameter and do necessary changes to call API from rest client as in the following:

http://localhost:21084/api/EmailNotifier/SendEmailNotification

HTTPPOST
    Content-Type: application/json  
    {  
       "UserName": "xyz",  
       "EmailId" : "[email protected]",  
    }  

Once you click on send button, you can verify input parameter by adding debug point to API in controller

After successful execution we will get response as follows:

Note: To send email you need to add actual email id and credential so that it will work as expected.



ASP.NET MVC Hosting - HostForLIFE.eu :: Learning About ASP.NET Core's MVC Application Life Cycle (.NET 6/7/8)

clock July 29, 2025 08:43 by author Peter

ASP.NET Core MVC: What Is It?
A lightweight, quick, and adaptable framework for creating web applications based on the Model-View-Controller paradigm is called ASP.NET Core MVC. It is open-source, cross-platform, and a component of the contemporary.NET ecosystem.

What makes it better than the old .NET Framework version?

  • Built-in Dependency Injection
  • Minimal startup code
  • Middleware pipeline instead of Global.asax
  • Easy configuration with Program.cs and appsettings.json

Basically, it gives us way more control and performance, while keeping things developer-friendly.

How a Request is Handled — Step by Step
Here’s what happens behind the scenes when someone hits your site.

1. Application Start – Program.cs
The old Startup.cs has merged into Program.cs (starting from .NET 6). This is where your app is bootstrapped.
var builder = WebApplication.CreateBuilder(args);

// Add services to the container
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}"
);

app.Run();


Tip: I like to keep this clean by offloading complex service setups into extension methods.

2. Middleware Pipeline
Think of middleware as a chain of events that the request passes through. You can inspect, modify, or even short-circuit the request before it reaches the controller.

Typical ones include:

  • Error handling (UseExceptionHandler)
  • Authentication
  • Logging
  • Static files
  • Routing

app.UseRouting(); // enables routing

3. Routing to Controllers
This is where ASP.NET Core figures out which controller and action to call.

For example
URL: /products/details/5
→ controller = ProductsController
→ action = details
→ id = 5


The route pattern in MapControllerRoute makes this work.

4. Controller is Created
The framework uses Dependency Injection to create your controller. If you’ve registered services in Program.cs, they’ll be injected automatically.
public class ProductsController : Controller
{
    private readonly IProductService _service;
    public ProductsController(IProductService service)
    {
        _service = service;
    }

    public IActionResult Details(int id)
    {
        var product = _service.GetProduct(id);
        return View(product);
    }
}


Note. Constructor injection like this helps keep things testable and clean.

5. Action Method is Called
ASP.NET Core figures out the action method to call (like Details) and even binds parameters from the route, query string, or body.
public IActionResult Details(int id)

It just works — no extra parsing needed.

6. Result is Returned
Your action method can return different types of results:

  • ViewResult → renders a Razor view
  • JsonResult → returns JSON
  • RedirectToAction → redirects

return View(product); // returns HTML view

7. View is Rendered
If you return a view, the Razor View Engine kicks in and converts your .cshtml into HTML, which is sent back to the browser.
// Returns Views/Products/Details.cshtml
return View(product);

Done!

Visual Flow of MVC Request in ASP.NET Core
Browser Request
     ↓ 
Kestrel Web Server
     ↓ 
Middleware Pipeline (auth, routing, logging)
     ↓ 
Routing System
     ↓ 
Controller (via DI)
     ↓ 
Action Method
     ↓ 
ActionResult (View, JSON, etc.)
     ↓ 
View Engine (if ViewResult)
     ↓ 
HTML Response to Browser

Key Pieces You Should Know

Component What It Does
Program.cs App startup: configures services and request pipeline
Middleware Handles cross-cutting concerns (auth, logging, error handling)
Routing Maps URLs to controllers/actions
Controller Processes logic for a specific request
Action Method Executes business logic, returns a result
View Engine Renders .cshtml to HTML

Best Practices I Follow

  • Use [FromRoute], [FromBody], etc. for clarity in parameter binding.
  • Keep Program.cs neat — move big configs to separate methods or files.
  • Inject services into controllers (not directly calling DbContext or static classes).
  • Use filters (e.g., Authorize, ActionFilter) for cross-cutting concerns.
  • Return typed ActionResult<T> in APIs for better structure.

Wrapping Up
So that’s how the ASP.NET Core MVC application life cycle works in .NET 6, 7, and 8. Whether you’re building simple web pages or full-blown APIs, understanding how a request moves through your app gives you the power, to optimize, troubleshoot, and architect like a pro.

Hope this guide helps you as much as it’s helped me.



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!



ASP.NET MVC Hosting - HostForLIFE.eu :: Bootstrap Modal PopUp Using ASP.NET MVC

clock June 20, 2025 08:20 by author Peter

We can show and hide the modal using the methods provided by Bootstrap Modal plugin.


Description
We are using modal ('show') and modal ('hide') methods to show and hide the login modal.

Reference
Before this article you should go through my Introduction to Bootstrap. Show Bootstrap Image Using Asp.Net MVC http://www.c-sharpcorner.com/blogs/bootstrap-image-show-using-asp-net-mvc3

Steps
Create a controller class file called "HomeController.cs" and add controller action method called "ModalPopUp()";
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.Mvc;  
  
namespace PeterMVCBootstrapImages.Controllers  
{  
    public class HomeController : Controller  
    {  
        //  
        // GET: /Home/  
  
        public ActionResult Index()  
        {  
            return View();  
        }  
  
        public ActionResult ModalPopUp()  
        {  
            return View();  
        }  
  
    }  


Then create a view file named "ModalPopUp.cshtml".
@{  
    ViewBag.Title = "
Peter Bootstrap PopUp";  
}  
  
<title>@ViewBag.Title</title>  
  
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">  
  
<style>  
    .button {  
        background-color: #4CAF50; /* Green */  
        border: none;  
        color: white;  
        padding: 15px 32px;  
        text-align: center;  
        text-decoration: none;  
        display: inline-block;  
        font-size: 16px;  
        margin: 4px 2px;  
        cursor: pointer;  
    }  
  
    .button1 {  
        border-radius: 2px;  
    }  
  
    .button2 {  
        border-radius: 4px;  
    }  
  
    .button3 {  
        border-radius: 8px;  
    }  
  
    .button4 {  
        border-radius: 12px;  
    }  
  
    .button5 {  
        border-radius: 50%;  
    }  
</style>  
<div>  
    <h2 style="background-color: Yellow;color: Blue; text-align: center; font-style: oblique">
Peter Bootstrap PopUp</h2>  
    <fieldset>  
        <legend style="color:orangered">Click On 
Peter Bootstrap PopUp</legend>  
        <div class="container">  
            <div class="row">  
                <div class="col-xs-12">  
  
                    <button id="btnShowModal" type="button"  
                            class="btn btn-sm btn-default pull-left col-lg-11 button button4">  
                        
Peter Modals  
                    </button>  
  
                    <div class="modal fade" tabindex="-1" id="loginModal"  
                         data-keyboard="false" data-backdrop="static">  
                        <div class="modal-dialog modal-lg">  
                            <div class="modal-content">  
                                <div class="modal-header">  
                                    <button type="button" class="close" data-dismiss="modal">  
                                        ×  
                                    </button>  
                                    <h4 class="modal-title">
Peter Login</h4>  
                                </div>  
                                <div class="modal-body">  
                                    <form>  
                                        <div class="form-group">  
                                            <input class="form-control" type="text"  
                                                   placeholder="Login Username" id="inputUserName" />  
                                        </div>  
                                        <div class="form-group">  
                                            <input class="form-control" placeholder="Login Password"  
                                                   type="password" id="inputPassword" />  
                                        </div>  
                                    </form>  
                                </div>  
                                <div class="modal-footer">  
                                    <button type="submit" class="btn btn-primary button button4">Sign</button>  
                                    <button type="button" id="btnHideModal" class="btn btn-primary button button4">  
                                        Hide  
                                    </button>  
                                </div>  
                            </div>  
                        </div>  
                    </div>  
  
                </div>  
            </div>  
        </div>  
    </fieldset>  
</div>  
    <footer>  
        <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">  
            ©  
            <script> document.write(new Date().toDateString()); </script>  
        </p>  
    </footer>  
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">  
    </script>  
    <script src="bootstrap/js/bootstrap.min.js"></script>  
  
    <script type="text/javascript">  
        $(document).ready(function () {  
            $("#btnShowModal").click(function () {  
                $("#loginModal").modal('show');  
            });  
  
            $("#btnHideModal").click(function () {  
                $("#loginModal").modal('hide');  
            });  
        });  
    </script> 

Here all reference files like bootstrap.min.css and jquery.min.js and bootstrap.min.js should be added to
add bootstrap features.
 
I have added code for a button to perform modal popup.
<button id="btnShowModal" type="button"  
       class="btn btn-sm btn-default pull-left col-lg-11 button button4">  
   
Peter Modals  
</button> 

I have added code for the modal form to appear in a fade style.
<div class="modal fade" tabindex="-1" id="loginModal"  
     data-keyboard="false" data-backdrop="static"> 
   

Here is the code for size of the modal.
<div class="modal-dialog modal-lg"> 

Controls are added Inside Modal content such as  header text , buttons, cross symbol button, text boxes and related control properties:
<div class="modal-content">  
    <div class="modal-header">  
        <button type="button" class="close" data-dismiss="modal">  
            ×  
        </button>  
        <h4 class="modal-title">
Peter Login</h4>  
    </div>  
    <div class="modal-body">  
        <form>  
            <div class="form-group">  
                <input class="form-control" type="text"  
                       placeholder="Login Username" id="inputUserName" />  
            </div>  
            <div class="form-group">  
                <input class="form-control" placeholder="Login Password"  
                       type="password" id="inputPassword" />  
            </div>  
        </form>  
    </div>  
    <div class="modal-footer">  
        <button type="submit" class="btn btn-primary button button4">Sign</button>  
        <button type="button" id="btnHideModal" class="btn btn-primary button button4">  
            Hide  
        </button>  
    </div>  
</div> 

For cross symbol button in header part.
<button type="button" class="close" data-dismiss="modal">  
    ×  
</button> 

For Header part.
<div class="modal-header">  
   <button type="button" class="close" data-dismiss="modal">  
       ×  
   </button>  
   <h4 class="modal-title">
Peter Login</h4>  
</div> 

For textBoxes

<div class="modal-body">  
    <form>  
        <div class="form-group">  
            <input class="form-control" type="text"  
                   placeholder="Login Username" id="inputUserName" />  
        </div>  
        <div class="form-group">  
            <input class="form-control" placeholder="Login Password"  
                   type="password" id="inputPassword" />  
        </div>  
    </form>  
</div> 


For footer part.
<div class="modal-footer">  
    <button type="submit" class="btn btn-primary button button4">Sign</button>  
    <button type="button" id="btnHideModal" class="btn btn-primary button button4">  
        Hide  
    </button>  
</div> 

Here I added one javascript and added button id such as btnShowModal and btnHideModal to show and hide modal.

<script type="text/javascript">  
    $(document).ready(function () {  
        $("#btnShowModal").click(function () {  
            $("#loginModal").modal('show');  
        });  

        $("#btnHideModal").click(function () {  
            $("#loginModal").modal('hide');  
        });  
    });  
</script> 


Here I added css style to add style in buttons.
<style>  
    .button {  
        background-color: #4CAF50; /* Green */  
        border: none;  
        color: white;  
        padding: 15px 32px;  
        text-align: center;  
        text-decoration: none;  
        display: inline-block;  
        font-size: 16px;  
        margin: 4px 2px;  
        cursor: pointer;  
    }  
  
    .button1 {  
        border-radius: 2px;  
    }  
  
    .button2 {  
        border-radius: 4px;  
    }  
  
    .button3 {  
        border-radius: 8px;  
    }  
  
    .button4 {  
        border-radius: 12px;  
    }  
  
    .button5 {  
        border-radius: 50%;  
    }  
</style>   




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