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

Internal JIT Compiler Enhancements in.NET 9

Leave a Comment

The Just-In-Time (JIT) compiler is one of the most critical components of the .NET 9 runtime. It converts Intermediate Language (IL) into optimized machine code at runtime.

With .NET 9, Microsoft has focused heavily on:

  • Faster startup time

  • Better runtime optimizations

  • Smarter code generation

  • Reduced CPU and memory usage

This article dives into the internals of JIT improvements and shows how they impact real-world performance.

What is the JIT Compiler?

When you compile C# code:

C# → IL (Intermediate Language) → JIT → Native Machine Code

The JIT compiler (RyuJIT) performs:

  • Method compilation at runtime

  • CPU-specific optimizations

  • Inlining and loop optimizations

Key JIT Improvements in .NET 9

1. Smarter Dynamic PGO (Profile-Guided Optimization)

What changed?

Dynamic PGO in .NET 9 is more aggressive and accurate:

  • Tracks real runtime behavior

  • Optimizes hot paths more efficiently

  • Rewrites frequently executed code

Example

public int Calculate(int x)
{
    if (x > 0)
        return x * 2;
    else
        return x - 2;
}

If most inputs are x > 0, JIT will:

  • Optimize the if branch

  • Reorder instructions for better CPU prediction

Benefit

  • Faster execution for real-world scenarios

  • Better branch prediction

2. Improved Method Inlining

What changed?

.NET 9 JIT:

  • Inlines more methods intelligently

  • Considers runtime behavior (not just size)

Example

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int Add(int a, int b) => a + b;

public int Calculate()
{
    return Add(10, 20);
}

JIT may inline Add() directly:

return 10 + 20;

Benefit

  • Eliminates function call overhead

  • Improves CPU cache usage

3. Loop Optimization Enhancements

Improvements

  • Loop unrolling

  • Bounds check elimination

  • Better vectorization

Example

for (int i = 0; i < arr.Length; i++)
{
    sum += arr[i];
}
C#

JIT optimizes:

  • Removes repeated bounds checks

  • Processes multiple elements per iteration

Benefit

  • Faster array processing

  • Ideal for data-heavy apps

4. SIMD & Hardware Intrinsics Expansion

What’s new?

Better support for:

  • AVX2 / AVX-512 instructions

  • ARM64 optimizations

Example

using System.Numerics;

Vector<int> v1 = new Vector<int>(new int[] {1,2,3,4});
Vector<int> v2 = new Vector<int>(new int[] {5,6,7,8});

var result = v1 + v2;
C#

JIT converts this into single CPU vector instruction

Benefit

Massive speed-up in:

  • Image processing

  • Scientific computing

  • AI workloads

5. Faster Tiered Compilation

Concept

.NET uses:

  • Tier 0 → Fast, minimal optimization

  • Tier 1 → Fully optimized

Improvement in .NET 9

  • Faster transition between tiers

  • Better hot-path detection

Benefit

Faster startup + optimized runtime

6. Reduced Register Spilling

Problem

When CPU registers are full → values go to memory (slow)

Improvement

  • Better register allocation strategy

  • Fewer memory writes

Benefit

  • Lower latency

  • Faster execution

7. Escape Analysis (Stack Allocation Optimization)

What’s new?

JIT can detect:

  • Objects that don’t escape method scope

Allocates them on stack instead of heap

Example

public struct Point
{
    public int X, Y;
}

public int Calculate()
{
    Point p = new Point { X = 10, Y = 20 };
    return p.X + p.Y;
}

No heap allocation → faster execution

Benefit

  • Reduced GC pressure

  • Faster memory access

Real Benchmark Scenario

Without Optimization

string result = "";
for (int i = 0; i < 1000; i++)
{
    result += i;
}

Causes:

  • Multiple allocations

  • GC overhead

Optimized (JIT + Best Practice)

var sb = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
    sb.Append(i);
}

Combined with JIT improvements:

  • Faster execution

  • Less memory usage

Behind the Scenes (JIT Pipeline)

  • IL Code Loaded

  • Tier 0 Compilation (quick)

  • Runtime Profiling (PGO collects data)

  • Tier 1 Recompilation (optimized)

  • Native Code Execution

Real-World Impact

These improvements benefit:

  • High-throughput APIs

  • Microservices

  • Gaming engines

  • Financial systems

  • Real-time analytics

Interview Questions

  • What is Tiered Compilation in .NET?

  • How does Dynamic PGO work?

  • What is method inlining and why is it useful?

  • How does JIT optimize loops?

  • What is escape analysis?

  • Difference between JIT and AOT?

Conclusion

The JIT improvements in .NET 9 make applications:

  • Faster

  • Smarter (runtime-aware optimizations)

  • More efficient (less memory and CPU usage)

Understanding these internals gives you a senior-level edge in:

  • Performance tuning

  • System design

  • Technical interviews

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

Best and Cheap nopCommerce 4.90.3 Hosting in Australia

Leave a Comment
Selecting the Best nopCommerce 4.90.3 Hosting in Australia, we'll offer you with the answer.  nopCommerce is the best open-source e-commerce shopping cart. nopCommerce is available for free. Today it's the best and most popular ASP.NET ecommerce software. It has been downloaded more than 1.8 million times! nopCommerce is a fully customizable shopping cart. It's stable and highly usable. nopCommerce is an open source ecommerce solution that is ASP.NET (MVC) based with a MS SQL 2008 (or higher) backend database. Our easy-to-use shopping cart solution is uniquely suited for merchants that have outgrown existing systems, and may be hosted with your current web host or our hosting partners. It has everything you need to get started in selling physical and digital goods over the internet.

https://ukwindowshostasp.net/UK-PrestaShop-Web-hosting

How to Choose the Best nopCommerce 4.90.3 Hosting in Australia?

DiscountService.biz is a line of business under Macrodata Enterprise (ABN: 42 797 697 621), specializes in providing web hosting service to customers in Australia. DiscountService.biz is an excellent nopCommerce 4.90.3 hosting provider focusing on providing rich-featured and super fast web hosting solutions to all kinds of customers ranging from personal bloggers to enterprises. Now webmasters wonder whether this company is good for nopCommerce 4.90.3 websites, so our editors conduct a comprehensive review on the company in price, features, usability, uptime, speed and technical support.

DiscountService.biz offers a variety of cheap and affordable Australia Windows ASP.NET Shared Hosting Plans to fit any need. No matter whether you’re starting a Blog with WordPress, installing a CMS solution with Drupal, opening a Forum with PHPBB, starting an Online Store with nopCommerce 4.90.3, or any number ventures beyond those mentioned above, our Windows ASP.NET Web Hosting plans are exactly what you’ve been looking for.
 
http://discountservice.biz/Australia-Moodle-1704-Hosting

DiscountService.biz nopCommerce 4.90.3 Hosting Review on Feature, Price and Performance
Available at this low price, the Beginner plan comes with sufficient web hosting resources and the latest versions of almost all the widely-used software, such as unlimited 2 GB Disk Space storage, 20GB monthly data transfer, unlimited hosted domains, PHP 5.5, MySQL 5.5, SQL 2008/2012/2014, etc. As a leading small to mid-sized business web hosting provider, they strive to offer the most technologically advanced hosting solutions available to their customers across the world. Security, reliability, and performance are at the core of their hosting operations to ensure each site and/or application hosted on their servers is highly secured and performs at optimum level. Unlike other web hosting companies, they do not overload their servers.

http://discountservice.biz/

All DiscountService.biz servers are equipped with minimum Intel Dual Processor Multi Core, 8 GM RAM and the fastest 1,000 Mbps connection backbone. This is to ensure that all sites hosted on their server has an access to the best performance, reliability and connectivity feature.

DiscountService.biz data center is located at Sydney, NSW. Their data centers are built upon a unique pod design concept, making them functionally independent with distinct and redundant resources, and fully integrated through their revolutionary network architecture. You can have direct control over your system in any data center and full access to all of their back-end services—all fully automated and on demand.

Support Service for Customers
DiscountService.biz has been committed to providing 24/7 qualified, experienced and patient customer supports via multitudes of supporting ways, like helpdesk, support ticket and email. It is proved that any issue can be handled as soon as possible. Furthermore, nopCommerce 4.90.3 customers can solve their problems by themselves via the guidance of NopCommerceTutorial & Articles, Discussion Board and Blog.

DiscountService.biz nopCommerce 4.90.3 Hosting is the Best Hosting in Australia
In short, DiscountService.biz offer nopCommerce 4.90.3 friendly hosting solutions which are featured rich, fast, reliable, and affordable. Taking these factors into consideration, DiscountService.biz is strongly recommended for people to host their nopCommerce 4.90.3 site.
Read More

ASP.NET Core Tutorial: How can the JSON Web Token (JWT) Structure be Validated?

Leave a Comment

A small, URL-safe token type called JSON Web Token (JWT) is used to safely transfer data as a JSON object between parties. It is extensively utilized in contemporary web applications, particularly in systems for authorization and authentication such microservices architectures, Node.js backends, and ASP.NET Core APIs.



In stateless authentication, when the server does not maintain session information, JWT is essential. Rather, the token itself contains all necessary user data, making it scalable and effective for cloud-based apps and distributed systems.

Secure authentication using JWT enhances application trust, user retention, and adherence to international security requirements from an SEO and GEO standpoint.

What is JWT?

A JSON Web Token (JWT) is an encoded string that contains claims (data) and is digitally signed to ensure integrity and authenticity. It is commonly used for:

  • User authentication

  • Authorization (role-based access)

  • Secure data exchange between services

A JWT is typically sent in the Authorization header as a Bearer token:

Authorization: Bearer

Structure of JWT

A JWT consists of three parts separated by dots:

Header.Payload.Signature

1. Header

The header contains metadata about the token, including the algorithm used for signing.

Example:

{
  "alg": "HS256",
  "typ": "JWT"
}
  • alg: Signing algorithm (HMAC SHA256, RSA, etc.)

  • typ: Token type

2. Payload

The payload contains claims (data). These can be:

  • Registered claims (iss, exp, sub)

  • Public claims

  • Private claims (custom data like userId, role)

Example:

{
  "userId": 101,
  "role": "Admin",
  "exp": 1716239022
}
3. Signature

The signature is used to verify that the token has not been tampered with.

Example:

HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secretKey
)

Real-World Scenario

Consider a login system in an e-commerce application. When a user logs in successfully, the server generates a JWT containing the user's ID and role. This token is sent to the client and included in future requests. The server validates the token before allowing access to protected resources.

How JWT Validation Works

Validating a JWT ensures that the token is authentic, not expired, and issued by a trusted authority.

Step-by-Step JWT Validation Process
Step 1: Decode the Token

Split the token into header, payload, and signature.

Step 2: Verify Signature

Ensure the signature matches using the secret key or public key.

Step 3: Check Expiration

Verify the exp claim to ensure the token is not expired.

Step 4: Validate Issuer and Audience

Check iss (issuer) and aud (audience) claims.

Step 5: Validate Claims

Ensure roles, permissions, and user data are valid.

JWT Validation in ASP.NET Core
builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "yourIssuer",
            ValidAudience = "yourAudience",
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes("yourSecretKey"))
        };
    });
Advantages of JWT
  • Stateless authentication (no server session storage)

  • Scalable for microservices

  • Compact and efficient

  • Secure with digital signatures

Disadvantages of JWT
  • Token cannot be easily revoked

  • Larger payload increases size

  • Security risks if secret key is compromised

JWT vs Session-Based Authentication
FeatureJWTSession-Based
StorageClient-sideServer-side
ScalabilityHighLimited
PerformanceFasterSlower
RevocationDifficultEasy
Use CaseAPIs, microservicesTraditional web apps

Best Practices for JWT Implementation
  • Use HTTPS to transmit tokens

  • Keep payload minimal

  • Set short expiration time

  • Use refresh tokens for long sessions

  • Store tokens securely (avoid localStorage for sensitive apps)

Real-World Use Cases
  • Authentication in REST APIs

  • Single Sign-On (SSO)

  • Mobile app authentication

  • Microservices communication

Summary

A small, URL-safe token type called JSON Web Token (JWT) is used to safely transfer data as a JSON object between parties. It is extensively utilized in contemporary web applications, particularly in systems for authorization and authentication such microservices architectures, Node.js backends, and ASP.NET Core APIs.

In stateless authentication, when the server does not maintain session information, JWT is essential. Rather, the token itself contains all necessary user data, making it scalable and effective for cloud-based apps and distributed systems.

Secure authentication using JWT enhances application trust, user retention, and adherence to international security requirements from an SEO and GEO standpoint.

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

How to Prevent Socket Exhaustion in .NET Core by Using HttpClientFactory?

Leave a Comment

Making HTTP calls to external APIs is a frequent practice when developing contemporary ASP.NET Core applications. You frequently utilize HttpClient to send requests, whether you are contacting a payment gateway, a third-party service, or another microservice.


However, a lot of developers unintentionally abuse HttpClient, which might cause socket exhaustion, a major issue. Because of this, when your program is under a lot of demand, it may slow down or even crash.

IHttpClientFactory, a potent feature that aids in the effective management of HttpClient instances, was added by.NET Core to address this issue.

This article explains socket exhaustion, explains why it occurs, and explains how to utilize HttpClientFactory in.NET. Step-by-step with basic examples.

What is Socket Exhaustion?

Understanding Socket Exhaustion in Simple Words

Socket exhaustion happens when your application creates too many HTTP connections and does not release them properly.

Each HTTP request uses a network socket. If sockets are not reused or closed correctly, the system runs out of available sockets.

Why This Happens with HttpClient

Many developers write code like this:

public async Task<string> GetData()
{
    using (var client = new HttpClient())
    {
        return await client.GetStringAsync("https://api.example.com/data");
    }
}

This looks correct, but creating a new HttpClient for every request causes:

  • Too many open connections

  • Delayed socket release (TIME_WAIT state)

  • Resource exhaustion

This leads to performance issues in ASP.NET Core applications.

What is IHttpClientFactory in .NET Core?

Simple Definition

IHttpClientFactory is a built-in factory in .NET Core that helps you create and manage HttpClient instances efficiently.

It handles:

  • Connection pooling

  • DNS updates

  • Lifetime management

Benefits of IHttpClientFactory

  • Prevents socket exhaustion

  • Improves performance

  • Centralized configuration

  • Better testability

Step 1: Create ASP.NET Core Project

dotnet new webapi -n HttpClientFactoryDemo
cd HttpClientFactoryDemo

Step 2: Register HttpClientFactory

Open Program.cs and add:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

// Register HttpClientFactory
builder.Services.AddHttpClient();

var app = builder.Build();

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

Step 3: Use IHttpClientFactory in Controller

Inject IHttpClientFactory

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class DemoController : ControllerBase
{
    private readonly IHttpClientFactory _httpClientFactory;

    public DemoController(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    [HttpGet]
    public async Task<IActionResult> Get()
    {
        var client = _httpClientFactory.CreateClient();

        var response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts");

        var data = await response.Content.ReadAsStringAsync();

        return Ok(data);
    }
}

Now HttpClient instances are managed efficiently.

Step 4: Named Clients

What are Named Clients?

Named clients allow you to configure different HttpClient instances for different APIs.

Configure Named Client

builder.Services.AddHttpClient("MyApi", client =>
{
    client.BaseAddress = new Uri("https://jsonplaceholder.typicode.com/");
    client.Timeout = TimeSpan.FromSeconds(10);
});

Use Named Client

var client = _httpClientFactory.CreateClient("MyApi");
var response = await client.GetAsync("posts");

Step 5: Typed Clients

What are Typed Clients?

Typed clients provide a clean and strongly-typed way to use HttpClient.

Create Typed Client

public class MyApiService
{
    private readonly HttpClient _httpClient;

    public MyApiService(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<string> GetPosts()
    {
        return await _httpClient.GetStringAsync("posts");
    }
}

Register Typed Client

builder.Services.AddHttpClient<MyApiService>(client =>
{
    client.BaseAddress = new Uri("https://jsonplaceholder.typicode.com/");
});

Use Typed Client

public class DemoController : ControllerBase
{
    private readonly MyApiService _service;

    public DemoController(MyApiService service)
    {
        _service = service;
    }

    [HttpGet]
    public async Task<IActionResult> Get()
    {
        var data = await _service.GetPosts();
        return Ok(data);
    }
}

Step 6: Configure HttpClient Handler Lifetime

To avoid DNS issues and reuse connections efficiently:

builder.Services.AddHttpClient("MyApi")
    .SetHandlerLifetime(TimeSpan.FromMinutes(5));

This ensures connections are refreshed periodically.

Step 7: Add Polly for Resilience

You can add retry policies using Polly:

builder.Services.AddHttpClient("MyApi")
    .AddTransientHttpErrorPolicy(policy =>
        policy.WaitAndRetryAsync(3, _ => TimeSpan.FromSeconds(2)));

This improves reliability in real-world applications.

Step 8: Best Practices

Follow These Best Practices

  • Always use IHttpClientFactory

  • Avoid creating HttpClient manually

  • Use named or typed clients

  • Configure timeouts

  • Add retry policies

Real-World Example

In a microservices architecture:

  • Service A calls Service B using HttpClientFactory

  • Connections are reused

  • Failures are handled with retries

This improves scalability and performance.

Summary

HttpClientFactory in .NET Core helps prevent socket exhaustion by managing HTTP connections efficiently through connection pooling and proper lifecycle management. Instead of creating multiple HttpClient instances, developers can use IHttpClientFactory to reuse connections, improve performance, and build scalable ASP.NET Core applications. Using named clients, typed clients, and resilience policies further enhances reliability and maintainability.

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

Important Distinctions Between gRPC and REST in.NET and When to Use Each

Leave a Comment

One of the most frequent queries developers have when creating APIs in.NET is: Should I use gRPC or REST?

Although they function differently and are appropriate for different situations, both are effective means of facilitating communication between services.

You may encounter performance problems, scalability challenges, or needless complexity if you use the incorrect strategy.

This guide will explain gRPC and REST in layman's terms, provide a clear comparison, and teach us when to utilize either in practical.NET applications.

What is REST?

REST (Representational State Transfer) is the most commonly used way to build APIs.

It works over HTTP and uses standard methods like:

  • GET → Fetch data

  • POST → Create data

  • PUT → Update data

  • DELETE → Remove data

REST APIs usually return data in JSON format, which is easy to read and widely supported.

In simple words:
REST is a simple and flexible way to build APIs that can be used by any client (web, mobile, etc.).

What is gRPC?

gRPC is a high-performance communication framework developed by Google.

It uses:

  • HTTP/2 (faster than HTTP/1.1)

  • Protocol Buffers (binary format instead of JSON)

Instead of sending plain JSON, gRPC sends compact binary data, which makes it faster and more efficient.

In simple words:
gRPC is a fast and efficient way for services to talk to each other.

Key Difference Between REST and gRPC (Explained Simply)

FeatureRESTgRPC
ProtocolHTTP/1.1HTTP/2
Data FormatJSON (text)Protobuf (binary)
SpeedModerateVery fast
ReadabilityEasyNot human-readable
StreamingLimitedBuilt-in support
Browser SupportExcellentLimited

How REST Works (Simple Flow)

  1. Client sends HTTP request (GET/POST)

  2. Server processes request

  3. Server returns JSON response

Example:

GET /api/products
HTTP

Response:

{
  "id": 1,
  "name": "Laptop"
}
JSON

This is simple and easy to debug.

How gRPC Works (Simple Flow)

  1. Define contract using .proto file

  2. Generate C# classes

  3. Client calls methods directly like functions

Example proto file:

service ProductService {
  rpc GetProduct (ProductRequest) returns (ProductResponse);
}
Proto

In gRPC, communication feels like calling a method instead of sending HTTP requests.

Step-by-Step: Create a gRPC Service in .NET

Step 1: Create gRPC Project

dotnet new grpc -n GrpcDemo
cd GrpcDemo
Bash

Step 2: Define Service in .proto File

syntax = "proto3";

service GreetingService {
  rpc SayHello (HelloRequest) returns (HelloResponse);
}

message HelloRequest {
  string name = 1;
}

message HelloResponse {
  string message = 1;
}
Proto

Step 3: Implement Service

public class GreetingService : GreetingService.GreetingServiceBase
{
    public override Task<HelloResponse> SayHello(HelloRequest request, ServerCallContext context)
    {
        return Task.FromResult(new HelloResponse
        {
            Message = "Hello " + request.Name
        });
    }
}
C#

Step 4: Call gRPC Service (Client)

var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new GreetingService.GreetingServiceClient(channel);

var reply = await client.SayHelloAsync(new HelloRequest { Name = "John" });

Console.WriteLine(reply.Message);
C#

When to Use REST?

Use REST when:

  • You are building public APIs

  • Your API is consumed by browsers or mobile apps

  • You need easy debugging (JSON)

  • Simplicity is more important than performance

When to Use gRPC?

Use gRPC when:

  • You are building microservices

  • You need high performance and low latency

  • Services communicate internally

  • You need streaming (real-time data)

REST vs gRPC in Microservices Architecture

In real-world systems:

  • REST is often used for external communication (client → server)

  • gRPC is used for internal communication (service → service)

This gives you both simplicity and performance.

Best Practices

  • Use REST for public-facing APIs

  • Use gRPC for internal services

  • Avoid mixing unnecessarily

  • Consider team experience and tooling

Real-World Example

E-commerce system:

  • Frontend → REST API

  • Backend services → gRPC communication

This ensures fast internal processing and simple external access.

Conclusion

Both REST and gRPC are powerful tools in .NET. The right choice depends on your use case.

If you need simplicity and wide compatibility, go with REST. If you need performance and efficiency for internal communication, gRPC is the better choice.

Understanding both will help you design better, scalable, and high-performance applications.

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

ASP.NET Tutorial: JWT Verification in the ASP.NET Core Web API

Leave a Comment

Security is one of the most important parts of any application. Today, most modern apps use token-based authentication instead of session-based login.

 One of the most popular methods is JWT (JSON Web Token) in ASP.NET Core.

 What is JWT?

JWT (JSON Web Token) is a secure token that is generated after login and used to access protected APIs.

Instead of storing user session on server, JWT stores data in token.

Simple Flow (Easy Understanding)

  • User Login

  • Server verifies user

  • Server generates JWT token

  • Client stores token

  • Client sends token in every request

  • Server validates token

Why JWT is Trending?

  • Stateless (No session needed)

  • Secure

  • Fast

  • Used in Mobile + Web APIs

  • Industry standard

Step 1: Create Web API Project

dotnet new webapi -n JwtAuthDemo

Step 2: Install Required Package

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Step 3: Configure JWT in Program.cs

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

var key = "ThisIsMySecretKey12345";

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = false,
        ValidateAudience = false,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key))
    };
});

builder.Services.AddAuthorization();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/", () => "JWT API Running");

app.Run();

Step 4: Create Token Generator

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

public class JwtService
{
    private string key = "ThisIsMySecretKey12345";

    public string GenerateToken(string username)
    {
        var claims = new[]
        {
            new Claim(ClaimTypes.Name, username)
        };

        var keyBytes = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
        var creds = new SigningCredentials(keyBytes, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            claims: claims,
            expires: DateTime.Now.AddMinutes(30),
            signingCredentials: creds
        );

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}

Step 5: Login API (Generate Token)

app.MapPost("/login", (string username, string password) =>
{
    if (username == "admin" && password == "123")
    {
        var jwt = new JwtService();
        var token = jwt.GenerateToken(username);

        return Results.Ok(token);
    }

    return Results.Unauthorized();
});

Step 6: Secure API

app.MapGet("/secure", () =>
{
    return "This is protected data";
}).RequireAuthorization();

How to Use in Postman

  • Call /login → get token

  • Copy token

  • Go to Headers

  • Add:

Authorization: Bearer YOUR_TOKEN
Plain text
  • Call /secure

Easy Understanding

  • Token = Identity Card 🪪

  • Without token ❌ access denied

  • With token ✅ access allowed

Real-Life Use Cases

  • Mobile apps login

  • Banking APIs

  • E-commerce systems

  • Microservices authentication

Conclusion

JWT authentication in ASP.NET Core is:

  • Secure

  • Fast

  • Widely used

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

Managing DB Null: The object cannot be cast from the database. To other types, null A C# error

Leave a Comment

The System exception is one of the most common ones that developers run into while working with ADO.NET and databases like Oracle or SQL Server.InvalidCastException. This typically occurs when the code attempts to directly convert a NULL value from a database field to a primitive type like int or decimal.



A database null in ADO.NET is represented by the DBNull instead of the C# null keyword.object of value. Your program dies because DBNull.Value cannot be cast straight to an integer. In this post, we'll examine how to organise your data access code using a secure Try-Catch architecture and build a reliable pattern to manage these nulls by defaulting them to 0.

Background

Imagine you are fetching commission rates from an Oracle database. Your table, UTILITIES_COMPANIES_COMM_RATES, has columns for CLIENTID and COMMISSIONRATE. If a specific record has no client assigned (a NULL value), the following code will fail:

// This line will throw an InvalidCastException if CLIENTID is NULL in the DB
ClientId = Convert.ToInt32(reader["CLIENTID"]);

To prevent this, we must verify the data before conversion.

Step-by-Step Implementation

1. Handling DBNull with the Ternary Operator

The simplest way to fix this is to use the ternary operator (? :) to check for DBNull.Value. If the value is null, we assign a default (like 0); otherwise, we perform the conversion.

int clientId = reader["CLIENTID"] == DBNull.Value ? 0 : Convert.ToInt32(reader["CLIENTID"]);

2. Implementing a Robust Repository Method

When writing for a production environment, it is best practice to wrap your database logic in a using statement (to handle connection closing) and a try-catch block (to handle errors).

Here is the full implementation for a GetAllCommissionRates method:

public List<UtilityCommissionRate> GetAllCommissionRates()
{
    var list = new List<UtilityCommissionRate>();
    string query = "SELECT ID, CLIENTID, COMMISSIONRATE, COMPANYID FROM UTILITIES_COMPANIES_COMM_RATES";

    // 'using' ensures the connection is closed even if an error occurs
    using (OracleConnection conn = new OracleConnection(_connectionString))
    {
        OracleCommand cmd = new OracleCommand(query, conn);

        try
        {
            conn.Open();
            using (OracleDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    list.Add(new UtilityCommissionRate
                    {
                        // Check each column for DBNull before converting
                        Id = reader["ID"] == DBNull.Value ? 0 : Convert.ToInt32(reader["ID"]),

                        ClientId = reader["CLIENTID"] == DBNull.Value ? 0 : Convert.ToInt32(reader["CLIENTID"]),

                        CommissionRate = reader["COMMISSIONRATE"] == DBNull.Value ? 0m : Convert.ToDecimal(reader["COMMISSIONRATE"]),

                        CompanyId = reader["COMPANYID"] == DBNull.Value ? 0 : Convert.ToInt32(reader["COMPANYID"])
                    });
                }
            }
        }
        catch (OracleException ex)
        {
            // Log database-specific errors (e.g., connection issues)
            Console.WriteLine($"Database Error: {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            // Log general conversion or logic errors
            Console.WriteLine($"General Error: {ex.Message}");
            throw;
        }
    }
    return list;
}

Creating a Cleaner Solution: Extension Methods

If you have a large project with many tables, checking for DBNull.Value in every line makes the code hard to read. We can solve this by creating a Generic Extension Method.

The Utility Class

public static class DataReaderExtensions
{
    public static T GetValueOrDefault<T>(this IDataRecord reader, string columnName)
    {
        object value = reader[columnName];
        return value == DBNull.Value ? default(T) : (T)Convert.ChangeType(value, typeof(T));
    }
}

Clean Usage

Now, your mapping code becomes much shorter and cleaner:

while (reader.Read())
{
    list.Add(new UtilityCommissionRate
    {
        Id = reader.GetValueOrDefault<int>("ID"),
        ClientId = reader.GetValueOrDefault<int>("CLIENTID"),
        CommissionRate = reader.GetValueOrDefault<decimal>("COMMISSIONRATE")
    });
}

Summary

  • The Problem: Convert.ToInt32 fails when it receives DBNull.Value.

  • The Fix: Use reader["column"] == DBNull.Value to check for nulls before casting.

  • Best Practice: Always use using blocks for OracleConnection to prevent memory leaks and connection pool exhaustion.

  • Pro Tip: Use extension methods to keep your repository code clean and maintainable.

Conclusion

Handling database nulls is a fundamental part of building stable .NET applications. By following the patterns above, you can ensure your application handles missing data gracefully without crashing.

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