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

ASP.NET Tutorial: C# 14 and.NET 10: The Game Has Changed

Leave a Comment

An explanation of the significance of this release from a major engineer.

The Morning Everything Clicked

I recall seeing the.NET 10 preview builds for the first time. It was one of those infrequent software moments when you realize you're looking at a fundamental change in how we'll develop applications rather than an incremental upgrade.

In addition to being speedier and more aesthetically pleasing,.NET 10 was released in November 2025 as an LTS version with three years of support. It's leaner, smarter, and, to be honest, the most exciting.NET release I've seen in a long time. This is the reason.

Speed: Not Just Fast, Ridiculously Fast

The JIT Got a PhD in Optimization

The Just-In-Time compiler in .NET 10 does something fascinating. Instead of simply organizing your code blocks in order, it treats the problem like the Travelling Salesman Problem—finding the optimal path through your code to minimize cache misses and branch mispredictions.

Remember all those times you wrestled with struct performance? The JIT now places struct members directly into registers instead of bouncing them through memory. It's like going from passing notes through a mailbox to just handing them directly to someone.

And the inlining? It's gotten recursive. When the compiler inlines a method and realizes "hey, now I can devirtualize this other call," it does it. Then it checks again. It's optimization all the way down.

Memory That Actually Makes Sense

Stack allocation has been expanded dramatically. Small arrays, local delegates, even reference type arrays in some cases—they can now live on the stack instead of adding to garbage collection pressure. In one benchmark I ran, GC pauses dropped by 20%. Twenty percent. That's the difference between a smooth user experience and a janky one.

The garbage collector itself got smarter too, with dynamic write-barrier switching now available on ARM64. If you're shipping to mobile or Apple Silicon, this matters.

C# 14: Less Boilerplate, More Clarity
Extension Members: Finally!

This is the headline feature, and for good reason. We've had extension methods since C# 3.0, but they always felt incomplete. Now we have extension properties, operators, and static members.

public implicit extension PointExtensions for System.Drawing.Point
{
    public double Magnitude => Math.Sqrt(source.X * source.X + source.Y * source.Y);

    public static Point operator +(Point left, Point right)
        => new Point(left.X + right.X, left.Y + right.Y);
}

// Now you can write:
var magnitude = myPoint.Magnitude;  // Clean!
var sum = point1 + point2;          // Natural!

Third-party types suddenly feel like they were designed for your use case. It's beautiful.

Spans Become First-Class Citizens

If you've been writing high-performance .NET code, you know Span<T>. But you've probably also typed .AsSpan() about a thousand times. Not anymore.

void ProcessData(ReadOnlySpan<int> data) { /* ... */ }

int[] array = { 1, 2, 3, 4, 5 };
ProcessData(array);  // Just works now

Implicit conversions. Everywhere. Performance-critical code just got more readable.

The field Keyword: Small but Mighty

Ever started with an auto-property, then needed to add validation?

// Before: Create a backing field, convert the property...
private string _name;
public string Name
{
    get => _name;
    set => _name = value?.Trim() ?? string.Empty;
}

// Now:
public string Name
{
    get => field;
    set => field = value?.Trim() ?? string.Empty;
}

The compiler manages the backing field. You write less code. Everyone wins.

Null-Conditional Assignment

This one saves so much ceremony:

// Before
if (customer is not null)
{
    customer.TotalSpent += orderAmount;
}

// After
customer?.TotalSpent += orderAmount;

The right side only evaluates if the left side isn't null. It's the little things.

Other Gems

  • nameof(List<>) - Works with unbound generics now

  • Lambda parameter modifiers - (out int result) in lambdas? Yes.

  • Partial constructors - Source generators rejoice

  • User-defined compound assignment - Less operator overload duplication

The AI Revolution Arrives in .NET

Here's where things get wild. .NET 10 includes the Microsoft Agent Framework, and it's not just another library—it's a vision for how we'll build intelligent applications.

One Interface to Rule Them All

IChatClient client = new OpenAIChatClient(apiKey, "gpt-4");
// Or Azure OpenAI, or Ollama, or...

var response = await client.CompleteAsync("Explain quantum computing");

Switch AI providers? Change one line. The abstraction is clean, the middleware is built-in, and the telemetry just works.

Model Context Protocol (MCP)

This is the secret sauce. MCP servers let your AI agents securely access external systems—databases, APIs, internal tools—without you having to wire up authentication and authorization from scratch.

You can even publish MCP servers as NuGet packages. Build once, reuse everywhere. The AI agent ecosystem just became composable.

dotnet new mcp-server -n MyCompanyDataAccess

The Supporting Cast

Post-Quantum Cryptography

Quantum computers are coming. .NET 10 is ready with ML-DSA, ML-KEM, and SLH-DSA algorithms. Your encrypted data won't become readable in 2030 when quantum computers arrive at scale.

WebSocketStream

Traditional WebSocket APIs are verbose. The new WebSocketStream wraps everything in a familiar Stream interface:

var stream = new WebSocketStream(ws, ownsWebSocket: true);
await stream.WriteAsync(data, cancellationToken);

No more manual buffer management. Just streams.

Async ZIP Operations

Finally. Creating and extracting ZIP files without blocking your UI thread:

var archive = await ZipArchive.CreateAsync(stream, ZipArchiveMode.Create);
var entry = await archive.CreateEntryAsync("data.txt");
await using var entryStream = await entry.OpenAsync();

JSON Improvements

Stricter serialization options, better throughput, PipeReader support. If you're building APIs, you'll notice the difference.

Framework Updates That Matter

ASP.NET Core 10

Blazor preloads WebAssembly components now, making initial loads noticeably faster. Passkey support in Identity means you can finally build passwordless auth properly. OpenAPI 3.1 generates better documentation with full JSON Schema 2020-12 support.

.NET MAUI

Multiple file selection in MediaPicker, WebView request interception, and Android API 35/36 support. Cross-platform development keeps getting smoother.

Entity Framework Core 10

Named query filters let you have multiple filters per entity and disable them selectively. The LINQ translator handles more complex queries. Performance optimizations make everything faster.

Real-World Impact

I refactored a text parsing service after upgrading to .NET 10. Changed maybe twenty lines to use new C# 14 features. Performance improved by 23%. GC pauses dropped by 15%. The code is cleaner. This isn't hype—it's measurable.

Should You Upgrade?

If you're starting a new project, absolutely. LTS support means you're covered for three years.

If you have existing apps, yes, but plan it. Most code just works, but the new span conversions might change overload resolution in edge cases. Test thoroughly.

If you're building AI-powered applications, this is your moment. The Agent Framework gives you a three-year head start.

The Bottom Line

.NET 10 and C# 14 represent something special a platform that's both mature and forward-thinking. The runtime is faster. The language is cleaner. AI integration isn't bolted on; it's built in.

Microsoft isn't just keeping up with modern development trends. With this release, they're setting them.

After twenty years of .NET evolution, watching it embrace AI-first development while maintaining backward compatibility and improving performance is remarkable. This is what great platform engineering looks like.

Time to upgrade. You won't regret it.

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

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