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

EF Core Split Queries: When and How to Use Them

Leave a Comment

When you eagerly load related data in Entity Framework Core (EF Core) using Include and ThenInclude, the framework can either generate a single large SQL query with multiple JOIN operations or execute several smaller queries (known as split queries). 

 

Selecting the appropriate strategy is essential, as an incorrect choice may lead to excessive row counts, high memory consumption, or additional network round trips. This article describes the concept of split queries, their purpose, safe usage practices, and scenarios where they outperform single-query approaches along with practical patterns for production environments.

The problem: JOINs, duplication, and the "Cartesian explosion"

Entity Framework combines tables with JOINs in a single query to obtain related data when using relational databases. Although SQL's JOIN operations are a basic functionality, their incorrect or ineffective implementation can cause significant performance overhead.This method is effective up until the query requires several collection navigations at the same level, after which the result set may expand significantly. 


JOIN actions duplicate the columns of the parent entity for every child row, even with a single collection inclusion. When the primary has a lot of columns, like pictures or long text, this can get expensive. To prevent retrieving needless huge columns, Entity Framework Core suggests utilizing projections.

var query = context.Customer
            .Include(o=>o.Orders)
            .Include(a=>a.Addresses)
            .Where(r=>r.Id==1);
Generated SQL

What are split queries?

Split queries instruct EF Core to divide a single LINQ query with Include statements into multiple SQL commands, typically one for each included collection. EF Core then assembles the results into the entity graph in memory, preventing the large, duplicated row sets that broad JOIN operations often produce.

Consider above mention example:

var query = context.Customer
            .Include(o=>o.Orders)
            .Include(a=>a.Addresses)
            .AsSplitQuery()
            .Where(r=>r.Id==1);

Generated SQL

When to Use Split Queries?

  • Multiple sibling collection includes
  • Large principal rows - If the principal entity contains large columns (such as images or BLOBs), JOIN duplication can significantly increase the payload size. In such cases, consider using split queries.
  • Complex graphs with deep relationships - EF Core’s caution regarding single-query eager loading of collections still applies; for queries with heavy includes, split queries are generally the safer default.

Enabling split queries globally (at the Context level)
You can also set split queries as the default behavior for your application's DbContext

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder
        .UseSqlServer(
            connectionString,
            o => o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery));
}

When split queries are set as the default, you can still configure individual queries to execute as single queries. Use caution when applying split queries in the following scenarios. Avoid Skip/Take with split queries unless ordering is unique - If you’re using split queries with Skip and Take in EF Core versions prior to 10, make sure your query has a unique ordering. If it doesn’t, the results might be wrong.

Prefer projections over Include for paged lists - Select only the data you need (e.g., project into DTOs) instead of including entire object graphs. This approach reduces payload size and prevents JOIN duplication

Conclusion
In EF Core, split queries are a useful and effective tool. When eagerly loading complicated object graphs, they assist minimize JOIN-related speed issues and eliminate data duplication, but they also add extra round trips and possible consistency issues. The optimal strategy varies depending on the situation: whenever you mix split queries with pagination, make sure the ordering is consistent, choose projections for paging, and assess both procedures using production-like data.

Use Split Queries When:

  • You include two or more collections at the same level.
  • Principal entities contain large columns (e.g., binary or text) that cannot be avoided.
  • You need predictable memory usage and reduced duplication.

Use Single Queries When:

  • Includes are primarily references rather than collections.
  • Network latency is high and additional round trips are expensive.
  • Strong consistency is required and you prefer a single SQL statement.

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

How Can File Uploads Be Securely Handled in a.NET Web API?

Leave a Comment

Many apps need to handle file uploads, including media files, papers, reports, profile photos, and more. However, there are security dangers associated with accepting user files. Attackers may upload malicious programs, large files, or malware that is camouflaged. For this reason, when developing a.NET Web API, secure file upload processing is essential. Using simple, approachable language, we will walk through the proper and secure implementation of file uploads in the.NET Web API in this post.

Use IFormFile to Receive the Uploaded File

IFormFile is the most straightforward method for handling uploads in the.NET Web API. An example of an endpoint

The simplest way to handle uploads in .NET Web API is using IFormFile.

Example Endpoint

[HttpPost("upload")]
public async Task<IActionResult> UploadFile(IFormFile file)
{
    if (file == null || file.Length == 0)
        return BadRequest("No file uploaded");

    return Ok("File received successfully");
}

Why This Works

  • Accepts uploaded files in multipart/form-data

  • Easy to validate and inspect

  • Works for images, documents, and media files

Apply File Size Limits to Prevent Abuse

Attackers may try to upload extremely large files to crash your server.

Set File Size Limit in Controller

if (file.Length > 5 * 1024 * 1024) // 5 MB
    return BadRequest("File is too large");

Configure Max Allowed Request Body in Program.cs

builder.WebHost.ConfigureKestrel(options =>
{
    options.Limits.MaxRequestBodySize = 10 * 1024 * 1024; // 10 MB
});

Why It Matters

  • Prevents denial-of-service attacks

  • Protects server memory and performance

Validate File Extensions and MIME Types

Attackers may upload .exe or .js files disguised as images.

Validate Extension

var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".pdf" };
var extension = Path.GetExtension(file.FileName).ToLower();

if (!allowedExtensions.Contains(extension))
    return BadRequest("Invalid file type");

Validate MIME Type

if (!file.ContentType.StartsWith("image") && file.ContentType != "application/pdf")
    return BadRequest("Invalid content type");

Why Validation Is Necessary

  • Prevent upload of malicious executable files

  • Ensures only expected formats reach your server

Generate a Safe File Name

Never use the original file name directly to avoid path traversal attacks.

Secure Name Generation

var safeFileName = Guid.NewGuid().ToString() + extension;

Why This Helps

  • Prevents overwriting existing files

  • Avoids user-controlled file paths

Store Files Outside the Web Root (Important!)

Never store uploaded files in the /wwwroot folder.

Secure Directory

/app_data/uploads/

Example Save Code

var filePath = Path.Combine(_env.ContentRootPath, "Uploads", safeFileName);

using (var stream = new FileStream(filePath, FileMode.Create))
{
    await file.CopyToAsync(stream);
}

Why Store Outside Web Root?

  • Prevents direct access to uploaded files

  • Stops attackers from executing uploaded files

Use Streaming for Very Large Files

IFormFile loads the file into memory. For large files, use streaming.

Example

[RequestSizeLimit(50_000_000)] // 50 MB
[HttpPost("stream-upload")]
public async Task<IActionResult> UploadLargeFile()
{
    var boundary = MultipartRequestHelper.GetBoundary(
        MediaTypeHeaderValue.Parse(Request.ContentType),
        50_000_000);

    // Stream logic here
    return Ok();
}

Why Streaming?

  • Avoids memory overload

  • Recommended for video, audio, large datasets

Scan Uploaded Files for Malware (Highly Recommended)

Use an antivirus engine like ClamAV, Windows Defender API, or third-party virus scanners.

Example (ClamAV)

var clam = new ClamClient("localhost", 3310);
var result = await clam.ScanFileOnServerAsync(filePath);

if (result.Result == ClamScanResults.VirusDetected)
{
    System.IO.File.Delete(filePath);
    return BadRequest("Malicious file detected");
}

Why Scan Uploaded Files?

  • Prevents malware distribution

  • Protects users and internal systems

Restrict Who Can Upload Files

Use authentication and authorization.

Example

[Authorize]
[HttpPost("upload-secure")]
public IActionResult UploadSecure(IFormFile file) {...}

Why?

  • Stops anonymous abuse

  • Limits uploads to trusted users

Log Every Upload Request

Logging helps in auditing and tracing suspicious activity.

Example

_logger.LogInformation("File uploaded: {FileName}, Size: {Size}", file.FileName, file.Length);

Why Logging Helps

  • Detects repeated malicious attempts

  • Supports forensic analysis

Use HTTPS for Secure File Transfer

Always use HTTPS when uploading files.

Benefits

  • Encrypts file content in transit

  • Prevents data interception

  • Protects user privacy

Best Practices for Secure File Uploads in .NET Web API
  • Validate file type and MIME type

  • Limit file size at multiple levels

  • Generate safe file names

  • Store uploads outside web root

  • Scan files for viruses

  • Use HTTPS for all uploads

  • Avoid using user input in file paths

  • Log all upload attempts

  • Use streaming for large files

  • Always secure upload endpoints with authentication

Conclusion

Secure file upload handling is essential for protecting your .NET Web API from potential attacks. By validating file types, restricting sizes, sanitizing file names, scanning for malware, and storing files safely, you greatly reduce security risks. Implementing these best practices ensures your application stays fast, secure, and reliable. With the right approach, you can confidently accept file uploads while keeping your system and users safe.

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 7.0.10 , 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

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
Previous PostOlder Posts Home