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

Comprehending QuickEHow to Quit Wasting Resources: An Introduction to .NET CancellationTokensndpoints in .NET

Leave a Comment

It is frequently necessary to stop an activity before it finishes in contemporary.NET Core applications, particularly those that include long-running activities, asynchronous actions, or HTTP requests. The CancellationToken is useful in this situation.


This article will explain what CancellationToken is, why it's necessary, how it functions, and how to use it using a basic example.

What is a CancellationToken?

CancellationToken in .NET Core is a mechanism to signal that an operation should be canceled. It allows tasks, loops, or asynchronous operations to cooperatively stop execution when requested.

Think of it as a “stop sign” you can pass to an operation. The operation checks this token periodically, and stops gracefully if cancellation is requested.

Why Do We Need CancellationToken?

Imagine a scenario where your application is performing a long-running task, like:

  • Downloading a large file

  • Processing millions of records

  • Calling an external API that might hang

Without a cancellation mechanism:

  • The operation will run until completion, wasting resources.

  • Users cannot stop operations if they change their mind.

  • It could lead to unresponsive applications.

CancellationToken solves this by allowing controlled, cooperative cancellation.

Key Components
  1. CancellationTokenSource (CTS)

    • Generates a CancellationToken.

    • Signals when cancellation is requested.

  2. CancellationToken

    • Passed to the task or method that needs to support cancellation.

    • Checked periodically to stop execution.

How to Use CancellationToken?

Step 1: Create a CancellationTokenSource

var cts = new CancellationTokenSource();
CancellationToken token = cts.Token;

Step 2: Pass the Token to an Operation

async Task DoWorkAsync(CancellationToken cancellationToken)
{
    for (int i = 0; i < 10; i++)
    {
        // Check if cancellation has been requested
        if (cancellationToken.IsCancellationRequested)
        {
            Console.WriteLine("Operation canceled!");
            return;
        }

        Console.WriteLine($"Working... {i + 1}");
        await Task.Delay(1000); // Simulate work
    }

    Console.WriteLine("Work completed successfully!");
}

Step 3: Request Cancellation

// Start the task
var task = DoWorkAsync(token);

// Cancel after 3 seconds
cts.CancelAfter(3000);

await task;

Output:

Working... 1
Working... 2
Working... 3
Operation canceled!

Notice how the task stops gracefully when cancellation is requested.

Use Cases for CancellationToken
  1. HTTP Requests
    Cancel an API call if it takes too long or the client disconnects.

  2. Background Services
    Stop background tasks in ASP.NET Core when the application shuts down.

  3. Long-Running Operations
    Allow users to cancel processes like file uploads, downloads, or heavy calculations.

Best Practices
  1. Always check IsCancellationRequested
    Inside loops or long operations.

  2. Throw OperationCanceledException for Tasks

    • In tasks, you can throw OperationCanceledException when canceled.

    • This ensures proper task cancellation and status handling.

cancellationToken.ThrowIfCancellationRequested();
  1. Pass the token to async methods that support it
    Many .NET Core methods like Task.Delay or HttpClient.SendAsync accept CancellationToken.

  2. Dispose CancellationTokenSource
    After use, dispose to free resources:

cts.Dispose();
Real-World Example: Cancel HTTP Request
using var cts = new CancellationTokenSource();
var client = new HttpClient();

try
{
    cts.CancelAfter(2000); // cancel after 2 seconds
    HttpResponseMessage response = await client.GetAsync("https://example.com/largefile", cts.Token);
    string content = await response.Content.ReadAsStringAsync();
    Console.WriteLine(content);
}
catch (OperationCanceledException)
{
    Console.WriteLine("HTTP request was canceled.");
}

This pattern is especially useful in web applications where users may navigate away or abort a request.

Advantages
Advantage
Graceful CancellationTasks stop safely without leaving the system in an inconsistent state.
Better Resource ManagementPrevent unnecessary CPU, memory, or network usage.
Improved User ExperienceUsers can cancel long-running operations instead of waiting.
Integrates with Async/AwaitWorks seamlessly with modern asynchronous programming patterns.

Conclusion
We've seen how CancellationToken is a potent and crucial tool for.NET Core developers in this article. It enables you to regulate execution, effectively manage resources, and enhance user experience whether you are creating long-running activities, background services, or API calls.

You may create software that is professional-grade, robust, and responsive by understanding how to use CancellationToken. I hope this is useful to you. Enjoy your reading!

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

ASP.NET Tutorial: .slnx is the new reality in.NET;.sln is retired

Leave a Comment

The.sln file quietly resided at the core of every.NET solution for almost twenty years.
The majority of developers hardly ever made manual edits. Many were afraid to touch it at all. In the hopes that it would "just work," nearly everyone submitted it to source control.

That period is coming to an end in contemporary.NET.

With the release of.NET 10, the SLNX solution file format—which was first available as a preview feature in the.NET 9 SDK (version 9.0.200 or later)—became the standard solution format.

Microsoft is making a clear change with the release of.slnx: solution files are now first-class, tool-friendly assets rather than IDE artifacts.

Although this modification may not seem significant at first, it signifies a significant advancement in the definition, versioning, and automation of.NET solutions. 

Why .sln No Longer Fits Modern .NET

The original .sln format was designed in a very different world:

  • Windows-first development

  • Visual Studio as the center of everything

  • Small, monolithic solutions

  • Minimal CI/CD automation

Over time, these assumptions broke down.

Real Problems with .sln

  • Proprietary and opaque format

  • Heavy reliance on GUIDs instead of intent

  • Extremely noisy Git diffs

  • Frequent merge conflicts

  • Hard to generate or modify programmatically

  • Tightly coupled to Visual Studio

In modern environments — cloud, containers, CI pipelines, mono-repos — .sln became friction instead of glue.

Enter .slnx: A Modern Solution Format

.slnx is not just a new extension. It is a re-thinking of what a solution file should be in today’s .NET ecosystem.

Core Design Goals of .slnx

  • Human-readable and declarative

  • Deterministic and diff-friendly

  • Tooling-agnostic

  • Easy to automate

  • Cross-platform by default

  • Ready for future tooling evolution

In short, .slnx describes what your solution is, not how a specific IDE manages it.

Side-by-Side: .sln vs .slnx

Classic .sln Example

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.34902.247
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyWebAppl", "src\MyWebAppl\MyWebAppl.csproj", "{A1B2C3D4-E5F6-7890-1234-567890ABCDEF}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyLibrary", "src\MyLibrary\MyLibrary.csproj", "{F0E9D8C7-B6A5-4321-FE09-87654321FEDC}"
EndProject
Global
    GlobalSection(SolutionConfigurationPlatforms) = preSolution
        Debug|Any CPU = Debug|Any CPU
        Release|Any CPU = Release|Any CPU
    EndGlobalSection
    // ... more complex sections
EndGlobal

Modern .slnx Example

<Project Sdk="Microsoft.Build.NoTargets">
  <PropertyGroup>
    <SolutionDir>$(SolutionDir)</SolutionDir>
    <SolutionGuid>...</SolutionGuid>
  </PropertyGroup>
  <ItemGroup>
    <ProjectReference Include="src\MyWebAppl\MyWebAppl.csproj" />
    <ProjectReference Include="src\MyLibrary\MyLibrary.csproj" />
  </ItemGroup>
</Project>

What This Comparison Tells Us

Aspect.sln.slnx
ReadabilityLowHigh
NoiseHighMinimal
GUID dependencyRequiredNot needed
Git diffsNoisyClean
AutomationFragileEasy
Cross-platformLimitedNative

This isn’t just cleaner — it’s structurally better.

Git, CI/CD, and Automation: Where .slnx Shines

Git Diffs (Real-World Scenario)

.sln diff:

- VisualStudioVersion = 17.7.34012.45
+ VisualStudioVersion = 17.8.34519.123

No functional change. Still causes conflicts.

.slnx diff:

+ <Project Path="Api/Api.csproj" />

Clear intent. Reviewable. Safe.

Why This Matters

  • Faster code reviews

  • Fewer merge conflicts

  • Reliable CI pipelines

  • Safer automation

This is especially important in:

  • Large teams

  • Mono-repos

  • Microservices architectures

Tooling-Agnostic by Design

.sln evolved as a Visual Studio artifact.
.slnx is designed for an ecosystem.

It works naturally with:

  • dotnet CLI

  • Visual Studio

  • CI/CD agents

  • Linux & macOS

  • Future editors and AI tooling

This aligns perfectly with modern .NET’s direction:

CLI-first, cloud-first, automation-first.

Large Solutions and Mono-Repos

As solutions grow:

  • .sln becomes slower to load

  • Merge conflicts increase

  • Manual fixes become common

.slnx is far better suited for:

  • Modular architectures

  • Multi-project repositories

  • Selective tooling and partial builds

Its declarative structure enables deterministic and scalable solution management.

Is .sln Gone Today?

No — and that’s intentional.

Microsoft is handling this transition responsibly:

  • .sln continues to work

  • .slnx adoption is incremental

  • No forced migration

  • Side-by-side coexistence

This mirrors previous successful transitions:

  • Old .csproj → SDK-style projects

  • Legacy build systems → modern MSBuild

The Bigger Picture: Why This Change Matters

On its own, .slnx may feel minor.

But history shows:

Seemingly boring infrastructure changes often unlock the biggest productivity gains.

.slnx is part of a broader .NET philosophy:

  • Less ceremony

  • More clarity

  • Better defaults

  • Tooling that scales with teams

This is how platforms mature.

What You Should Know About .SLNX

  1. Works Across Tools and Platforms: .slnx is supported not only in Visual Studio, but also in the .NET CLI, MSBuild, and VS Code, making solution management consistent no matter which tool or OS you use.

  2. Seamless Migration from Existing .sln Files: You can convert existing .sln files to .slnx easily via the .NET CLI or directly from Visual Studio using “Save Solution As…”, allowing a smooth transition without disrupting your workflow.

  3. Compatible with Solution Filters: If your projects use .slnf files (solution filters), they continue to work after migration — you just need to point them to the new .slnx file.

  4. Extensions Continue to Work: Most Visual Studio extensions that interact with solution files will continue functioning, though extensions that edit solution files directly may require updates to fully support .slnx.

  5. Recommended Single-Format Strategy: While both .sln and .slnx can exist temporarily during a phased migration, it’s best for teams to standardize on .slnx to avoid confusion and ensure smooth automation.

  6. XML-Based for Clarity and Tooling: The .slnx format uses XML, which is widely supported and easier to read and automate than the old .sln text format. It aligns solution representation with .csproj files, simplifying cross-tool usage.

  7. Minimum Tooling Requirements: To work with .slnx, ensure you’re using Visual Studio 17.13+ or .NET SDK 9.0.200+, so all tools in your environment understand the new format.

These points are summarized and interpreted from guidance shared by the Visual Studio team to help developers transition confidently to the new .slnx solution format.

Key Takeaways

.sln served .NET well — but it belongs to a different era.

.slnx represents:

  • Modern collaboration

  • Clean source control

  • Cloud-native development

  • Future-ready tooling

It’s not flashy. It’s not loud. But it will quietly improve the daily lives of .NET developers for years.

Sometimes the most important improvements are the ones you don’t notice — until they’re gone.

HostForLIFE is Best Option for ASP.NET Core 10.0 Hosting in Europe

Frankly speaking, HostForLIFE is best option to host your ASP.NET Core 10.0 Hosting in Europe. You just need to spend €2.97/month to host your site with them and you can install the latest ASP.NET Core 10.0 via their Plesk control panel. We would highly recommend them as your ASP.NET Core 9.0 Hosting in Europe.

http://hostforlifeasp.net/European-ASPNET-Core-2-Hosting
Read More

Using Server Sent Events to Create Real Time ModernServer Push in .NET

Leave a Comment

As engineers, we adore strong instruments. Web sockets. Message brokers, SignalR. frameworks for real-time that are stacked on top of one another. However, after years of developing and managing production systems, I've discovered something unsettling:

Most real-time features are overengineered.

Very often, the problem is simple:

  • “Show live status updates”

  • “Stream progress from the server”

  • “Notify users when something changes”

For these cases, Server-Sent Events (SSE) is usually the better answer — and it’s already built into the web platform and ASP.NET Core.

Let’s talk about what SSE really iswhen it makes sense, and how to implement it cleanly in ASP.NET Core.

What Server-Sent Events Actually Are

Server-Sent Events are:

  • standard HTTP connection

  • Kept open by the server

  • Used to push text-based events from server → client

That’s it.

No protocol upgrades.
No bi-directional messaging.
No abstraction layers hiding what’s happening.

From the browser side, SSE is supported natively using EventSource.

From the server side, it’s just HTTP streaming.

SSE vs WebSockets (The Honest Comparison)

WebSockets are powerful — but power comes with cost.

Here’s the architectural reality:

RequirementSSEWebSockets
Server → Client updates
Client → Server messaging
Uses standard HTTP
Easy to debug
Auto-reconnect✅ (browser)❌ (manual)
ComplexityLowMedium–High

If your feature is:

  • Status updates

  • Notifications

  • Progress streaming

  • Monitoring dashboards

WebSockets are usually unnecessary.

SSE is simpler, safer, and easier to maintain.

Why SSE Fits ASP.NET Core So Well

ASP.NET Core is built around:

  • Async I/O

  • Streaming responses

  • Cooperative cancellation

  • High-performance HTTP handling

SSE fits this model perfectly.

You:

  • Open a request

  • Write events as they happen

  • Flush the response

  • Let the client handle reconnection

No special middleware.
No extra packages.
No magic.

Server-Sent Events vs SignalR

AspectServer-Sent Events (SSE)SignalR
Communication modelOne-way (Server → Client)Bi-directional (Server ↔ Client)
TransportStandard HTTP (text/event-stream)WebSockets with fallbacks
Client → Server messaging❌ Not supported✅ Fully supported
ComplexityLowMedium to High
Learning curveMinimalModerate
Browser supportNative via EventSourceRequires SignalR client
Automatic reconnection✅ Built-in (browser-managed)⚠️ Manual / framework-managed
DebuggabilityEasy (plain HTTP)Harder (abstracted transports)
Scalability modelPredictable, HTTP-basedRequires backplane at scale
Infrastructure needsNone beyond HTTPRedis / Azure SignalR at scale
Best suited forNotifications, status updates, progress streamingChat, collaboration, real-time apps
Operational overheadLowMedium
Failure handlingSimple, gracefulMore moving parts

How to choose (rule of thumb)

  • Choose SSE when your system is server-driven, events flow in one direction, and operational simplicity matters.

  • Choose SignalR when your application requires real-time interaction, client input, or collaborative features.

A Simple, Working SSE Example in ASP.NET Core

Let’s build a real example — not a toy abstraction.

Scenario

The server sends a live update every second:

  • Timestamp

  • Incrementing counter

This pattern maps directly to:

  • Job progress

  • System metrics

  • Order tracking

  • Background task updates

Server Side: ASP.NET Core API

Controller

using Microsoft.AspNetCore.Mvc;using System.Text;

[ApiController][Route("api/events")]public class EventsController : ControllerBase{
    [HttpGet("stream")]
    public async Task Stream(CancellationToken cancellationToken)
    {
        Response.Headers.Append("Content-Type", "text/event-stream");
        Response.Headers.Append("Cache-Control", "no-cache");
        Response.Headers.Append("Connection", "keep-alive");

        var counter = 0;

        while (!cancellationToken.IsCancellationRequested)
        {
            var data = $"data: Time: {DateTime.UtcNow:O}, Count: {counter++}\n\n";
            var bytes = Encoding.UTF8.GetBytes(data);

            await Response.Body.WriteAsync(bytes, cancellationToken);
            await Response.Body.FlushAsync(cancellationToken);

            await Task.Delay(1000, cancellationToken);
        }
    }}

Why This Code Is Production-Friendly

  • Fully async

  • No thread blocking

  • Proper cancellation support

  • Immediate flushing

  • Minimal surface area

When the browser disconnects, RequestAborted cancels automatically — no leaks.

Client Side: Browser (Vanilla JavaScript)

<!DOCTYPE html><html><head>
    <title>SSE Demo</title></head><body>
    <h2>Live Server Events</h2>
    <pre id="output"></pre>

    <script>
        const output = document.getElementById("output");
        const source = new EventSource("/api/events/stream");

        source.onmessage = (event) => {
            output.textContent += event.data + "\n";
        };

        source.onerror = () => {
            output.textContent += "Connection lost. Reconnecting...\n";
        };
    </script></body></html>

The browser:

  • Opens one HTTP connection

  • Automatically reconnects

  • Handles network issues gracefully

You get real-time updates with almost no code.

Important Architectural Considerations

This is where senior experience matters.

1. Connection Count

Each client holds one open connection.

  • Fine for hundreds or thousands

  • Beyond that, plan horizontal scaling

2. Stateless Servers

SSE works best when:

  • Events come from a shared source

  • Redis, Kafka, Service Bus, etc.

The SSE endpoint just streams — it doesn’t own state.

3. Authorization

SSE respects:

  • Cookies

  • JWT

  • ASP.NET Core authorization policies

Secure it like any other endpoint.

When SSE Is the Wrong Choice

Don’t force it.

Avoid SSE if:

  • You need bi-directional messaging

  • You’re building chat

  • You need binary payloads

  • You require ultra-low latency interaction

That’s where WebSockets or SignalR shine.

Final Thoughts

They’re not flashy. They’re not trendy. And that’s exactly why Server-Sent Events work so well. When your real-time requirements are one-way, driven entirely by the server, predictable in behavior, and easy to operate at scale, SSE often turns out to be the cleanest architectural choice in ASP.NET Core. It avoids unnecessary complexity, fits naturally into the HTTP model, and remains easy to reason about in production. Sometimes, the best engineering decision isn’t about using the most powerful tool it’s about choosing the boring one that quietly does its job, day after day, without surprises.

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

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