Meet The Author

I'm Ethan Jackson, An 25 years old blogger Currently living in London, United Kingdom. I'm a Skilled Blogger, Part Time web Developer And Creating new things as a web Designer.

author

ASPHostPortal Officially Launches ASP.NET Core 10.0 Hosting: Faster, More Secure, and Built for Modern Web Apps

Leave a Comment


If you're a developer who keeps up with Microsoft’s latest technologies, here’s big news you don’t want to miss. ASPHostPortal, one of the world’s leading ASP.NET hosting providers, has officially released ASP.NET Core 10.0 Hosting. This massive upgrade brings better performance, stronger security, and more flexibility for building modern web applications.

What’s New in ASP.NET Core 10.0?

ASP.NET Core 10.0 introduces powerful enhancements that help developers build faster and work more efficiently. Some of the standout features include:

Improved Runtime Performance

Optimizations in the pipeline make ASP.NET Core 10.0 applications run faster and more responsively.

Enhanced Minimal APIs

Cleaner and more streamlined, allowing developers to build lightweight APIs quicker than ever.

Stronger Security Features

Upgraded authentication and authorization systems ensure better protection for enterprise-grade apps.

Better Cloud-Native Integration

ASP.NET Core 10.0 is more optimized for containers, Kubernetes, and modern cloud platforms.

With these upgrades, building modern, scalable, and cloud-ready applications becomes easier and more efficient.

Why Choose ASPHostPortal for ASP.NET Core 10.0 Hosting?

ASPHostPortal has long been known for delivering high-performance, stable, and .NET-focused hosting solutions. The launch of ASP.NET Core 10.0 Hosting further reinforces their commitment to supporting the newest Microsoft technologies early and reliably.

Here’s what makes ASPHostPortal a top choice:

Servers Optimized for ASP.NET Core 10.0

Their hosting environment is fine-tuned to ensure maximum performance.

Fast SSD Storage + Free SSL Certificate

Your website loads faster and stays secure—without extra fees.

Easy Deployment with cPanel/Plesk

Deploy your ASP.NET Core apps with just a few clicks.

24/7 Expert Technical Support

A support team that truly understands the ASP.NET ecosystem.

Affordable Pricing

Perfect for startups, small businesses, and large enterprises.

Who Should Use ASP.NET Core 10.0 Hosting?

The new hosting environment is ideal for:

  • Developers exploring the latest .NET features

  • Businesses needing secure and high-speed websites

  • Startups building cloud-native applications

  • Companies running high-performance APIs

  • Existing ASP.NET users upgrading their tech

If you want future-ready applications, now is the best time to move to ASP.NET Core 10.0.

Conclusion

The release of ASP.NET Core 10.0 Hosting by ASPHostPortal marks an exciting step forward for developers wanting to level up their web applications. With top-tier performance, robust security, and full support for the latest .NET framework, this hosting plan is fully prepared for today’s and tomorrow’s needs.

Ready to try it? Visit ASPHostPortal’s official website and start building with ASP.NET Core 10.0 Hosting today! 

Read More

Five ASP.NET Core Hidden Treasures You Most Likely Don't Use

Leave a Comment

Unlock robust built-in features to enhance your ASP.NET Core apps' dependability, performance, and maintainability. Although there are many fantastic capabilities in ASP.NET Core, many developers just utilize the most fundamental ones, such as controllers, middleware, dependency injection, EF Core, and authentication. Strong utilities that can significantly enhance your applications without the need for complicated setups or third-party libraries are hidden within the framework.



The five underappreciated ASP.NET Core capabilities that most developers ignore but should definitely start utilizing in contemporary apps are examined in this post. Among these characteristics are:

These features include:

  1. Background task processing with IHostedService

  2. Built-in Health Checks

  3. Endpoint Filters in ASP.NET Core 8

  4. HTTP/3 support

  5. Rate Limiting Middleware

Each of these features can help you build:

  • Faster apps

  • More stable APIs

  • Cleaner architecture

  • Better user experiences

Let’s dive into each gem in detail.

1. IHostedService for Background Tasks

The first hidden gem is using IHostedService to run recurring background tasks without external libraries like Hangfire or Quartz.

What is IHostedService?

IHostedService allows you to run background processes inside your ASP.NET Core application, such as:

  • Sending emails

  • Cleaning up expired records

  • Processing queues

  • Generating reports

  • Sending periodic notifications

And the best part?

  • No external scheduler required

  • Runs inside your application lifecycle

How It Works?

The Implementation using a timer to run recurring jobs:

public class BackgroundTask : IHostedService, IDisposable
{
    private Timer? _timer;

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromMinutes(1));
        return Task.CompletedTask;
    }

    private void DoWork(object? state)
    {
        Console.WriteLine("Running background task...");
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _timer?.Change(Timeout.Infinite, 0);
        return Task.CompletedTask;
    }

    public void Dispose() => _timer?.Dispose();
}
C#

Register it:

builder.Services.AddHostedService<BackgroundTask>();
C#

When to Use It

Use IHostedService when you need:

  • Recurring jobs

  • Background operations

  • Timed processing

  • Queue workers

2. Built-in Health Checks

The Health Checks as a hidden but powerful feature for monitoring application health.

What Are Health Checks?

Health Checks allow your application to report the status of:

  • Database connections

  • Disk storage

  • External services

  • APIs

  • Custom dependencies

This is extremely valuable for production environments.

Why It Matters

This feature ensures your critical dependencies remain in good shape.

Systems like:

  • Kubernetes

  • Load balancers

  • Monitoring dashboards

Can automatically detect if your service is unhealthy and restart or reroute traffic.

3. Endpoint Filters in ASP.NET Core 8

Introduced in ASP.NET Core 8 and works like middleware but with more granular control.

What Are Endpoint Filters?

They allow you to apply logic only to specific endpoints, such as:

  • Validation

  • Logging

  • Response formatting

Unlike traditional middleware, endpoint filters target individual routes.

Why It’s Useful

The endpoint filters help avoid repetitive code and create cleaner APIs with centralised logic.

4. HTTP/3 Support

ASP.NET Core now includes HTTP/3 support out of the box, providing major performance improvements for modern applications.

Benefits of HTTP/3

HTTP/3 offers:

  • Reduced latency

  • Faster data transfer

  • Better performance for unreliable networks

Performance gains apply especially to:

  • Streaming video

  • Gaming

  • Real-time applications

How to Enable HTTP/3

The enabling HTTP/3 via appsettings configuration:

"Kestrel": {
  "Endpoints": {
    "HttpsDefault": {
      "Url": "https://localhost:5001",
      "Protocols": "Http1AndHttp2AndHttp3"
    }
  }
}

5. Rate Limiting Middleware

The final feature is the new Rate Limiting Middleware in ASP.NET Core.

Why Rate Limiting Matters

If you’re building public APIs, you must protect them from:

  • Abuse

  • Flooding

  • DDoS-style traffic

  • Overuse

This middleware helps maintain stable performance under heavy load.

Example

builder.Services.AddRateLimiter(options =>
{
    options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(
        context => RateLimitPartition.GetFixedWindowLimiter(
            "default",
            _ => new FixedWindowRateLimiterOptions
            {
                PermitLimit = 5,
                Window = TimeSpan.FromSeconds(10)
            }));
});

app.UseRateLimiter();

This limits clients to 5 requests per 10 seconds.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2012 R2, SQL Server 2014, ASP.NET 7.0.4, ASP.NET MVC 6.0, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
 

 

Read More

Use Visual Studio to Instantly Convert JSON or XML to C# Classes

Leave a Comment

You've undoubtedly encountered this scenario if you've ever used an API in.NET:

  • You need to deserialize the massive JSON or XML answer you receive from the API into C# classes.
  • You get your hands dirty and begin manually inputting properties.
  • After writing six lessons in ten minutes, you're already exhausted.

 

The good news? You no longer have to endure suffering. With only a few clicks, you can convert JSON or XML into completely structured C# classes using an integrated tool in Visual Studio. You won't use manual typing again after you figure out this secret.

The Visual Studio feature "Paste Special"
The Edit → Paste Special menu in Visual Studio contains a hidden treasure.

  • Copy and paste JSON as classes
  • Copy and paste XML as classes

These scripts rapidly create C# classes that are identical to raw JSON or XML from your clipboard.
No extensions. No external tools. No packages from NuGet. Just Visual Studio. 

How to Use It (Step by Step)?
Step 1: Copy Your JSON or XML

Copy the JSON or XML from Postman, Swagger, or your API response.
Example JSON
{

  "id": 101,

  "name": "Laptop",

  "price": 1299.99,

  "specs": {

    "processor": "Intel i7",

    "ram": "16GB",

    "storage": "512GB SSD"

  }

}


Step 2: Open a C# File

Open your project in Visual Studio and create an empty class file under the Models folder. 


Step 3: Use "Paste Special"
Action: Go to the Visual Studio menu Edit → Paste Special → Paste JSON as Classes (or Paste XML as Classes ).

Step 4: Boom - Your Classes Appear


Why This Feature is a Life Saver

  • Time saver: Seconds instead of minutes or hours.
  • Error-free: No more typos in property names.
  • Brain-friendly: Focus on logic, not typing.
  • Great for prototyping: Quickly test APIs without manually creating models.

The first time I discovered this feature, I literally facepalmed because I had been hand-writing JSON classes for years. Since then, I’ve shown it to dozens of developers — and every time, their reaction is the same:

“Wait… this was in Visual Studio all along?!”

So if you’ve been struggling with API responses, stop wasting time. Next time you get a JSON or XML payload, just:

Copy → Paste Special → Done.

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 10.0, ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

Using Request.Form[UniqueID] to Safely Retrieve Encrypted Form Values in ASP.NET

Leave a Comment

Form controls, such as hidden fields, textboxes, or HTML input elements, are frequently used to hold temporary or encrypted values when creating secure ASP.NET applications. During postback, these frequently store information such as encrypted PAN numbers, OTP tokens, or encrypted session keys.

A typical pattern looks like this:
string encryptedText = Request.Form[hdnPANEnc.UniqueID];
// or
string encryptedText = Request.Form[panidvalue.UniqueID];

But many developers wonder:

“Is this safe? Will it throw an error? Are there any disadvantages?”

Let’s break this down step by step and understand how it works internally — and how to use it safely.
Understanding How Request.Form[UniqueID] Works

ASP.NET Web Forms uses a naming container hierarchy, meaning every control is given a unique, fully qualified name in the rendered HTML.

When a form is posted, ASP.NET automatically maps each posted field back to the server control using that control’s UniqueID.

Example Controls
<input type="hidden" name="ctl00$MainContent$hdnPANEnc" value="ENCRYPTED_DATA" />

<asp:HiddenField ID="hdnPANEnc" runat="server" />

<asp:TextBox ID="Panidvalue" runat="server" placeholder="Enter PAN"></asp:TextBox>

<input type="text" id="Panid" value="" placeholder="Enter PAN" autocomplete="off" />


Server-side Retrieval

string encryptedText = Request.Form[hdnPANEnc.UniqueID];
// or
string encryptedText = Request.Form[Panidvalue.UniqueID];


This correctly retrieves the posted value — whether it comes from a hidden field or a textbox — after a postback.

Why It’s Safe and Reliable

It does not throw exceptions if the field exists in the posted form.
It’s the recommended method for accessing posted values outside data-binding or control events.

ASP.NET automatically URL-decodes form data, so encrypted strings containing +, /, or = are handled safely.

You can safely use it to retrieve encrypted or masked values (like PAN, OTP, or token data).
Possible Disadvantages and Caveats

Although this approach works perfectly, you should be aware of a few potential caveats:
 

1. Hidden Fields Are Visible in Browser Developer Tools
Even encrypted data stored in a hidden field can be seen and modified using browser “Inspect Element.”

Best Practice
Always decrypt and validate the value on the server side before using it.
string encryptedText = Request.Form[hdnPANEnc.UniqueID];
if (!string.IsNullOrEmpty(encryptedText))
{
    encryptedText = HttpUtility.UrlDecode(encryptedText);
    string decryptedPAN = Decrypt(encryptedText);
    // Re-validate with DB or checksum if required
}


2. ID Changes in Nested Controls
When a control exists inside a Master Page, Repeater, or UpdatePanel, its HTML name changes dynamically.

Using .UniqueID ensures ASP.NET can still map the posted form value correctly.

Using .ID may fail because it only represents the local control name, not the full hierarchy.

You’re already doing it correctly with .UniqueID.

3. AJAX or Custom POST Requests
If your form is submitted using JavaScript (e.g., fetch() or $.ajax()), hidden or textbox values might not post unless you serialize the entire form properly.

Example
var formData = new FormData(document.getElementById("form1"));
fetch('YourPage.aspx', {
    method: 'POST',
    body: formData
});


This ensures all form controls, including hidden fields and textboxes, are sent to the server.

4. Encoding Issues (Rare)

Some encryption outputs (like Base64) contain characters such as +, /, or =.
Browsers automatically URL-encode them during submission.

To avoid decoding mismatches:
string encryptedText = HttpUtility.UrlDecode(Request.Form[hdnPANEnc.UniqueID]);

Security Best Practices
RecommendationDescription
Encrypt sensitive dataBefore assigning values to hidden fields or textboxes
Decrypt & validate server-sideNever trust client-side values directly
Avoid plain text storageNever expose PAN, UPI ID, or passwords
Use ViewState encryption or SessionFor higher security and tamper-proof data

Final Verdict
CheckpointResult
Works without errorsYes
Safe to useYes (with encryption)
Handles nested controlsYes
Security caveatsHidden fields are user-editable
RecommendedYes, with server-side validation

Example Secure Implementation

ASPX

<asp:HiddenField ID="hdnPANEnc" runat="server" />
<asp:TextBox ID="Panidvalue" runat="server" placeholder="Enter PAN"></asp:TextBox>
C# (Code-Behind)
// Encrypt and assign value
hdnPANEnc.Value = Encrypt(userPAN);

// Retrieve securely during postback
string encryptedText = Request.Form[hdnPANEnc.UniqueID];
if (!string.IsNullOrEmpty(encryptedText))
{
    string decryptedPAN = Decrypt(HttpUtility.UrlDecode(encryptedText));
    // Use decryptedPAN safely after validation
}

// Also handle textbox input
string inputPAN = Request.Form[Panidvalue.UniqueID];
if (!string.IsNullOrEmpty(inputPAN))
{
    // Optionally encrypt, sanitize, or validate here
}
Conclusion

Using Request.Form[control.UniqueID] — whether for a hidden field, textbox, or custom <input> — is a reliable, efficient, and flexible way to retrieve posted values in ASP.NET Web Forms.

Just remember

  • It won’t throw errors if the field exists.

  • It automatically handles URL-decoding.

  • The only risk lies in trusting client-side data — always decrypt and verify it on the server.

By following these best practices, you ensure both security and stability in your ASP.NET form-handling logic.

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 10.0 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

Background Tasks Using Hosted Services in ASP.NET Core Without Hangfire

Leave a Comment

Sending emails, clearing away old logs, processing files, and updating reports are just a few examples of the background tasks that are frequently required in real-world systems without interfering with user requests.

Many developers immediately turn to frameworks such as Azure Functions, Quartz.NET, or Hangfire.
However, what if you're looking for something integrated directly into ASP.NET Core, lightweight, and dependency-free?

The answer is:
Hosted Services — a powerful built-in feature in ASP.NET Core to run background tasks efficiently.

This article will show you how to build background jobs without Hangfire, step-by-step.

1. What Are Background Jobs?

A background job is any process that runs behind the scenes — not directly triggered by a user and not part of the main request/response flow.

Common Examples
  • Sending order confirmation emails after checkout

  • Generating and emailing PDF reports

  • Cleaning up temporary files

  • Syncing data with third-party APIs at intervals

These tasks can take time, and you don't want them to slow down user requests.
That's where Hosted Services come in.

2. What Are Hosted Services in ASP.NET Core?

ASP.NET Core includes a background task framework out of the box using IHostedService.

You can think of it as a service that starts with your application and runs continuously in the background.

There are mainly two types:

  1. IHostedService – Run logic at startup and shutdown.

  2. BackgroundService – A helper base class for continuous or scheduled jobs.

3. Architecture Overview

Below is a high-level diagram of how Hosted Services work in ASP.NET Core.

Flowchart: Background Job Architecture
+----------------------------------+
| ASP.NET Core Application         |
| (Web API / MVC / Razor / Blazor) |
+-------------------+--------------+
                    |
                    v
+----------------------------------+
| Hosted Service (Background Task) |
| - Runs Independently             |
| - Starts with Application        |
| - Handles Long/Recurring Jobs    |
+-------------------+--------------+
                    |
                    v
+----------------------------------+
| Services / Database / APIs       |
| (Email, File System, Cleanup)    |
+----------------------------------+
4. Step-by-Step Implementation

Let's create a simple background job that runs every 5 minutes and cleans up old logs from the database.

Step 1: Create the Hosted Service Class
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

public class LogCleanupService : BackgroundService
{
    private readonly ILogger<LogCleanupService> _logger;
    private readonly IServiceProvider _serviceProvider;

    public LogCleanupService(ILogger<LogCleanupService> logger, IServiceProvider serviceProvider)
    {
        _logger = logger;
        _serviceProvider = serviceProvider;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Log Cleanup Service started.");

        while (!stoppingToken.IsCancellationRequested)
        {
            await DoCleanupAsync();
            await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken); // Runs every 5 minutes
        }

        _logger.LogInformation("Log Cleanup Service stopped.");
    }

    private async Task DoCleanupAsync()
    {
        try
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                var dbContext = scope.ServiceProvider.GetRequiredService<MyAppDbContext>();

                var oldLogs = dbContext.Logs
                    .Where(l => l.CreatedDate < DateTime.UtcNow.AddDays(-30))
                    .ToList();

                dbContext.Logs.RemoveRange(oldLogs);
                await dbContext.SaveChangesAsync();

                _logger.LogInformation($"{oldLogs.Count} old logs cleaned up successfully.");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error while cleaning up logs.");
        }
    }
}
Step 2: Register the Service in Program.cs
var builder = WebApplication.CreateBuilder(args);

// Register your Hosted Service
builder.Services.AddHostedService<LogCleanupService>();

// Register DbContext and other dependencies
builder.Services.AddDbContext<MyAppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

var app = builder.Build();

app.MapControllers();
app.Run();

That's it!
Now your background service will automatically start when the application starts.

5. Handling Dependency Injection

When working inside a background service, never directly inject scoped services (like DbContext).
Instead, use IServiceProvider.CreateScope() — as shown above — to create a new service scope.

This ensures clean resource management and prevents memory leaks.

6. Adding Multiple Background Services

You can register multiple hosted services — each handling a different task:

builder.Services.AddHostedService<EmailSenderService>();
builder.Services.AddHostedService<DataSyncService>();
builder.Services.AddHostedService<ReportGeneratorService>();

Each one will run independently in its own background thread.

7. Graceful Shutdown and Cancellation

ASP.NET Core automatically handles graceful shutdowns for hosted services.
When the app stops (or is restarted), it sends a cancellation token (stoppingToken) to stop the job safely.

To handle it cleanly:

if (stoppingToken.IsCancellationRequested)
{
    _logger.LogInformation("Service stopping...");
    break;
}

8. Advanced Scenarios

Scheduled Jobs

You can make jobs run at specific times using Cronos (a lightweight Cron parser):

using Cronos;

private readonly CronExpression _cron = CronExpression.Parse("0 * * * *"); // every hour

Then calculate the next occurrence using:

var next = _cron.GetNextOccurrence(DateTime.UtcNow);

Queue-Based Background Processing

For more complex use cases (like queued background tasks), use BackgroundTaskQueue with Channel or ConcurrentQueue.

9. Benefits of Using Hosted Services

FeatureBenefit
No extra dependencyBuilt directly into .NET Core
LightweightIdeal for microservices and small apps
ReliableStarts/stops with the app lifecycle
FlexibleRun periodic, continuous, or one-time tasks
SecureFull DI and configuration support

10. When Not to Use Hosted Services

  • For long-running or heavy workloads, use Azure Functions, Worker Services, or Hangfire.

  • For distributed job coordination, prefer message queues (RabbitMQ, Kafka).

  • Hosted Services are best for simple, internal background tasks within a single app instance.

Conclusion

You don't always need heavy frameworks like Hangfire for background processing.
ASP.NET Core's Hosted Services provide a clean, native way to manage background jobs — with full integration into dependency injection, logging, and configuration.

They're:

  • Simple to build

  • Reliable to run

  • Perfect for small to medium workloads

By mastering Hosted Services, you gain a powerful tool to run scheduled, continuous, or on-demand background tasks all without adding any external library.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 10.0, ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/

 

Read More

How to Create Custom Middleware in ASP.NET Core?

Leave a Comment

Middleware: What is it?
A middleware is a little piece of software that handles HTTP requests and responses in ASP.NET Core.
Every middleware operates in a pipeline and is capable of:

  • Execute a task prior to the subsequent middleware execution.
  • After it runs, take a certain action, or
  • even prevent the request from being processed further.

To put it simply, middleware can examine, alter, or end a request or response, much like a checkpoint in the request pipeline.

Default Middleware Examples

ASP.NET Core comes with built-in middleware such as:

  • UseRouting() — Handles URL routing

  • UseAuthentication() — Handles login/auth

  • UseAuthorization() — Manages access control

  • UseStaticFiles() — Serves static files like images or CSS

You can also create your own custom middleware to add specific logic (like logging, validation, or tracking).

Step-by-Step: Creating Custom Middleware

Let’s create a simple custom middleware that logs each incoming request and outgoing response.

Step 1. Create the Middleware Class
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using System;

public class MyCustomMiddleware
{
    private readonly RequestDelegate _next;

    // Constructor to accept the next middleware in the pipeline
    public MyCustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    // Main method to handle request and response
    public async Task InvokeAsync(HttpContext context)
    {
        // Code before the next middleware runs
        Console.WriteLine($" Request received: {context.Request.Method} {context.Request.Path}");

        // Call the next middleware in the pipeline
        await _next(context);

        // Code after the next middleware runs
        Console.WriteLine($" Response sent: {context.Response.StatusCode}");
    }
}
Step 2. Create an Extension Method (for cleaner code)

It’s good practice to add an extension method so you can easily use your middleware.

using Microsoft.AspNetCore.Builder;

public static class MyCustomMiddlewareExtensions
{
    public static IApplicationBuilder UseMyCustomMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<MyCustomMiddleware>();
    }
}
Step 3. Register the Middleware in Program.cs

In .NET 6+, middleware is added in the request pipeline using the app object.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// Custom middleware registration
app.UseMyCustomMiddleware();

// Example controller routing
app.MapControllers();

app.Run();

Step 4. Run and Test

Now run your application (Ctrl + F5).

When you send a request (like GET /api/values), you’ll see logs in the console:

Request received: GET /api/values
Response sent: 200

Your custom middleware successfully intercepted and logged the request and response!

How Middleware Works Internally?

When a request comes in:

  1. The first middleware receives it.

  2. It can do something (like logging) and call the next middleware.

  3. The request flows through all middleware components.

  4. The response flows back through them in reverse order.

Visual Flow Diagram
Request → [Middleware 1] → [Middleware 2] → [Middleware 3] → Endpoint
             ↑                                      ↓
          Response ← [Middleware 3] ← [Middleware 2] ← [Middleware 1]
When to Use Custom Middleware

Custom middleware is useful for:

  • Logging requests and responses

  • Handling exceptions globally

  • Adding custom headers or tokens

  • Measuring performance

  • Implementing request filters (e.g., IP blocking)

Example: Adding a Header Middleware

Here’s another short example that adds a custom header to all responses:

public class HeaderMiddleware
{
    private readonly RequestDelegate _next;

    public HeaderMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        await _next(context);
        context.Response.Headers.Add("X-Powered-By", "SandhiyaCustomMiddleware");
    }
}

Register it in Program.cs:

app.UseMiddleware<HeaderMiddleware>();

Every response from your app will now include:

X-Powered-By: SandhiyaCustomMiddleware

Summary

StepAction
1Create a middleware class with InvokeAsync(HttpContext)
2Add an extension method for better reusability
3Register it in the request pipeline using the app.UseMyCustomMiddleware()
4Test by sending a request and checking the console or response headers

Conclusion

Custom middleware gives you complete control over the request and response pipeline in ASP.NET Core.

It helps you write clean, reusable, and centralized logic for logging, authentication, or any pre/post-processing.

In short: Middleware is the heart of ASP.NET Core request handling — and custom middleware lets you extend that heart for your unique business needs.

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 10.0 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

Jenkins CI/CD for ASP.NET Core + Angular App Deployment

Leave a Comment

Applications built using Angular for the frontend and ASP.NET Core for the backend are frequently deployed by hand, requiring file copies, Visual Studio publishing, IIS restarts, and other steps. Manual deployment becomes dangerous as your team increases, although it works well for small projects. One minor error could overwrite settings or result in downtime.

Jenkins' Continuous Integration and Continuous Deployment (CI/CD) technology can help with it.
Every time you push code, it swiftly and safely builds, tests, and deploys your project. I'll walk you through the process of utilizing the Jenkins pipeline to deploy a full-stack application (Angular + ASP.NET Core) on a Windows server (IIS) in this post.

Requirements

Before we start, make sure you have:

  • Installed Jenkins (Windows or Linux)

  • Installed .NET SDK (e.g. .NET 8.0) on the Jenkins server

  • Installed Node.js and Angular CLI

  • Installed Git (for source code checkout)

  • Access to your IIS server for deployment

Project Structure

Below is a common folder structure we’ll work with:

HFLDemoApp/
 ├── WebAPI/             # ASP.NET Core Backend
 ├── ClientApp/          # Angular Frontend
 ├── Jenkinsfile         # Jenkins pipeline script
 ├── deploy.ps1          # PowerShell script for IIS deployment

Step 1. Create a Jenkins Pipeline Job

  1. Open Jenkins Dashboard → New Item → Pipeline

  2. Give it a name, e.g., RajeshDemoApp-CI-CD

  3. Under Pipeline definition, select Pipeline script from SCM

  4. Choose Git, and provide your repo URL.

  5. Jenkins will now read the Jenkinsfile from your repository.

Step 2. Jenkinsfile Configuration

Here’s a simple Jenkinsfile example for our project:

pipeline {
    agent any

    stages {
        stage('Checkout Code') {
            steps {
                git branch: 'main', url: 'https://github.com/your-repo'
            }
        }

        stage('Build Angular') {
            steps {
                dir('ClientApp') {
                    bat 'npm install'
                    bat 'ng build --configuration production'
                }
            }
        }

        stage('Build .NET Core') {
            steps {
                dir('WebAPI') {
                    bat 'dotnet restore'
                    bat 'dotnet publish -c Release -r win-x64 -o ../publish'
                }
            }
        }

        stage('Deploy to IIS') {
            steps {
                bat 'powershell .\\deploy.ps1'
            }
        }
    }
}

Note:
If you’re using Linux agents, replace bat with sh.

Step 3. Create PowerShell Script for Deployment

Let’s create a PowerShell file named deploy.ps1 at the root of your repo.

This script will:

  • Stop IIS site

  • Backup old files

  • Copy new build files

  • Restart IIS site

Write-Host "Starting deployment..."

$source = "C:\Jenkins\workspace\MyApp-CI-CD\publish"
$destination = "C:\inetpub\wwwroot\RajeshDemoApp"
$backup = "C:\Backup\MyApp_" + (Get-Date -Format "yyyyMMdd_HHmmss")

# Stop IIS
iisreset /stop

# Backup existing site
if (Test-Path $destination) {
    Copy-Item $destination $backup -Recurse
    Write-Host "Backup created at $backup"
}

# Copy new files
Copy-Item $source\* $destination -Recurse -Force

# Start IIS
iisreset /start

Write-Host "Deployment completed successfully."

Step 4. Handle Configuration Files

We usually have environment-specific files like:

  • appsettings.Production.json

  • environment.prod.ts

You can use a small PowerShell snippet to replace these files based on environment before publishing.

Example:

Copy-Item ".\Configs\Production\appsettings.json" ".\WebAPI\appsettings.json" -Force

Step 5. Run the Pipeline

  1. Commit and push your code (including Jenkinsfile).

  2. Go to Jenkins → click Build Now.

  3. Jenkins will run each stage — build Angular, build .NET, deploy to IIS.

Step 6. Troubleshooting Tips

If deployment fails:

  • Check Jenkins console logs (very helpful).

  • Make sure IIS user has write permission to your deployment folder.

  • Ensure Node.js, Angular CLI, and .NET SDK paths are configured in Jenkins.

Step 7. Benefits of Using CI/CD

After setting this up once, your deployments become:

  • Automatic – no manual file copying

  • Consistent – same steps every time

  • Fast – 1-click deployment from Jenkins

  • Safe – automatic backup and rollback

Conclusion

By combining Jenkins, ASP.NET Core, and Angular, we can automate our entire deployment process.

No more “it works on my machine” issues — your build, test, and deployment happen exactly the same way every time.

Windows Hosting Recommendation

HostForLIFE receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 10.0 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More
Previous PostOlder Posts Home