European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET Core 9.0 Hosting - HostForLIFE :: In Clean Code, Null Coalescing vs. Null Conditional

clock February 17, 2025 07:14 by author Peter

I will illustrate Null Coalescing (??) and Null Conditional (?.) in this article. Programmers frequently struggle with null references, although contemporary languages like C# provide sophisticated solutions. Two separate but complimentary methods for creating safe and clear code are the null conditional operator (?.) and the null coalescing operator (??). This page explains how to use them, gives examples, and examines their capabilities.

What is Null Coalescing (??)?
The null coalescing operator (??) provides a fallback value when a variable is null, serving as a concise alternative to traditional null-checking if statements.

Syntax
result = variable ?? fallbackValue;

How does Null Coalescing (??) work?
If variable is not null, its value is assigned to result.
If variable is null, the fallbackValue is assigned instead.
    string userName = null;
   string displayName = userName ?? "Guest User";
   Console.WriteLine(displayName);

The null coalescing operator (??) simplifies null-checking logic.

In this example, displayName is guaranteed to have a value, even if userName is null.

This approach is more concise and readable compared to an equivalent if statement:
The traditional method to achieve this before the introduction of ??
string displayName;
if (userName != null)
{
    displayName = userName;
}
else
{
    displayName = "Guest";
}

When to use the null coalescing operator (??)

Default Values: Assign a default value when a variable is null.

Dictionary<string, string> userPreferences = new Dictionary<string, string>()
        {
            { "theme", "dark" },
            { "language", "en" }
        };

// Use ?? to provide a default value if the key doesn't exist
string theme = userPreferences.GetValueOrDefault("theme") ?? "light";
string fontSize = userPreferences.GetValueOrDefault("fontSize") ?? "medium";

Console.WriteLine($"Theme: {theme}");       // Output: Theme: dark
Console.WriteLine($"Font Size: {fontSize}"); // Output: Font Size: medium


Output

  • Theme: dark   => requested value exists in the dictionary, so it will return the same value
  • Font Size: medium  => requested values do not exist, then it will return default values provided using the null coalescing operator (??)

Chained Fallbacks: Provide multiple fallback options.
string preferredName = null;
string alternateName = null;
        
// Use ?? to check both variables and provide a default value if both are null
string displayName = preferredName ?? alternateName ?? "Unknown Person";
Console.WriteLine(displayName);  // Output: Unknown Person


Output
"Unknown Person" because both variable assigned with null value.

  • The null coalescing operator can be chained to check multiple variables.
  • The operator will return the first non-null value from the chain.
  • If all variables are null, it will return the last fallback value. In this case, "Unknown".

The traditional method to achieve multiple null checks before the introduction of ??
string preferredName = null;
string alternateName = null;

// Traditional method using if statements
string displayName;

 if (preferredName != null)
 {
     displayName = preferredName;
}
 else if (alternateName != null)
  {
     displayName = alternateName;
  }
  else
  {
     displayName = "Unknown Person";
  }

Console.WriteLine(displayName);  // Output: Unknown Person

What is Null Conditional (?.)

The null conditional operator ?. allows safe navigation of objects and their properties, avoiding null reference exceptions. It short-circuits evaluation if the object or property being accessed is null.
result = object?.Property;

How does Null Conditional (?.) work?
public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public int Id { get; set; }
    public string City { get; set; }
    public string PinCode { get; set; }
}
Person person = null;

 // Use the null conditional operator to safely access a property
 string name = person?.Name ?? "Unknown";

 Console.WriteLine(name);  // Output: Unknown

 string persionCity = person?.Address?.City ?? "London"; // If person or Address object null then it will assign default city as London
The null conditional operator (?.) is used to safely access the Name property of person. Since person is null, person?.Name will return null.
When to use Null Conditional (?.)

  • The null conditional operator (?.) allows you to safely access properties or methods of potentially null objects without throwing exceptions.
  • It can be chained to access multiple levels of properties, like person?.Address?.City.
  • It works well in scenarios where the object might be null and you want to avoid explicit null checks.

Comparing Null Coalescing (??) and Null Conditional (?.)
Null Coalescing (??)

  • Use it when you need to provide a fallback value if an expression evaluates to null.
  • It's commonly used in scenarios involving value assignment or default parameters.

Null Conditional (?.)

  • Use it when you need to safely access or call properties and methods on potentially null objects.
  • It's frequently used in deep object hierarchies or when dealing with nullable types.

Combining Both ?? and ?
Consider the example above with the Person class, which has an Address reference, and we want to use a combination of both ?? and ?. to check for null. Here's how we can implement it:
string userCity = person?.Address?.City ?? "Unknown City";
Console.WriteLine(userCity); // Output: Unknown City


Summary
In this article, we have examined how to handle null checks more efficiently by utilizing C#'s Null Coalescing (??) and Null Conditional (?.) operators. We discussed how these features can be applied to implement null checks in a cleaner, more readable manner, improving both the clarity and maintainability of the code. Additionally, we explored how to use these operators individually as well as how to combine them in a single statement to handle multiple null checks effectively, making the code more concise and eliminating the need for verbose null-checking logic.

Feel free to follow me here, and you can read more articles at this link: Click Here to explore my articles.

  • New LINQ Methods in .NET 9: Index, CountBy, and AggregateBy
  • Working with JSON in .NET Core: Newtonsoft.Json, NetJSON, and System.Text.Json
  • Implement a retry policy in .NET 6 Applications with Polly
  • Understanding Model Binding in ASP.NET Core with .NET 8
  • Data Conversions in C# with SuperConvert


European ASP.NET Core 9.0 Hosting - HostForLIFE :: How to Use Middleware for Rate Limiting in.NET?

clock February 14, 2025 06:16 by author Peter

Any application or API that is made available to the public must include rate limitation. It guards against harmful attacks including denial-of-service (DoS) attacks, guarantees equitable utilization among clients, and stops resource exhaustion. We'll go over what rate limiting is, why it's important, and how to use Visual Studio's tools to create it in.NET in this comprehensive guide.

What is Rate Limiting?
Rate limiting is the practice of controlling the number of requests a client can make to a server within a specific time period. It ensures that resources are distributed fairly and that a single client cannot overwhelm the system.

Why Implement Rate Limiting?

Here’s why rate limiting is vital.

  • Prevent System Overload: Protect your server from being overwhelmed by a flood of requests.
  • Ensure Fair Usage: Distribute resources equitably among users.
  • Mitigate Attacks: Defend against DoS attacks or API abuse.
  • Cost Control: Avoid unnecessary resource consumption, especially in cloud-based systems.
  • Improve Stability: Enhance the reliability and performance of your application.

Setting Up Rate Limiting in .NET Using Visual Studio
.NET 7 introduces a built-in rate-limiting middleware that simplifies the implementation of rate limits. Follow these detailed steps using Visual Studio to integrate this feature into your application.

Step 1. Create a New Web API Project

  • Open Visual Studio.
  • Click on Create a new project.
  • Select ASP.NET Core Web API and click Next.
  • Name your project (e.g., RateLimitingExample) and click Next.

Choose .NET 7 as the framework and click Create.
This creates a new Web API project with the required dependencies.

Step 2. Add Rate Limiting Middleware
To implement rate limiting, configure the middleware in the Program.cs file.

Open the Program.cs file.
Add rate-limiting policies to control the traffic flow. Replace the existing content with the following code.
using Microsoft.AspNetCore.RateLimiting;
using System.Threading.RateLimiting;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Configure rate limiting policies
builder.Services.AddRateLimiter(options =>
{
    options.AddPolicy("FixedWindowPolicy", context =>
        RateLimitPartition.GetFixedWindowLimiter(
            partitionKey: context.Connection.RemoteIpAddress?.ToString() ?? "default",
            factory: _ => new FixedWindowRateLimiterOptions
            {
                PermitLimit = 10, // Allow 10 requests
                Window = TimeSpan.FromSeconds(10), // Within 10 seconds
                QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
                QueueLimit = 2 // Allow 2 requests in queue
            }));
});

var app = builder.Build();
// Use rate limiting middleware
app.UseRateLimiter();
// Map endpoints
app.MapControllers();
app.Run();


Step 3. Add a Controller

  • Right-click on the Controllers folder in Solution Explorer.
  • Select Add > Controller.
  • Choose API Controller – Empty and name it WeatherForecastController.
  • Replace the contents of the generated file with the following code.

using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]
    [EnableRateLimiting("FixedWindowPolicy")]
    public IActionResult GetWeather()
    {
        return Ok(new { Message = "Weather data retrieved successfully!" });
    }
}


This controller applies the FixedWindowPolicy rate limit to the GetWeather action.

Step 4. Test the Application

  • Press F5 or click Start to run the application.
  • Open your browser, Postman, or another API testing tool.
  • Send multiple GET requests to the endpoint:
  • http://localhost:<port>/WeatherForecast After 10 requests within 10 seconds, the API will return a 429 Too Many Requests response.

Advanced Features of Rate Limiting
The built-in middleware allows you to customize rate-limiting strategies further.

  • Sliding Window Policy: Provides smoother rate limiting by spreading limits across smaller time segments.
  • Token Bucket Policy: Allows short bursts of requests but enforces an overall rate limit.
  • Concurrency Policy: Limits the number of simultaneous requests processed by the server.

You can define these policies in the Program.cs file is similar to the fixed window example.

Consequences of Not Using Rate Limiting

Without rate limiting, your application might face.

  • Resource Exhaustion: Overloaded servers, slower response times, and potential crashes.
  • Unfair Usage: A single client can monopolize resources, leaving others without access.
  • Security Risks: Increased vulnerability to DoS attacks and brute-force attempts.
  • Higher Costs: Excessive resource consumption can drive up operational expenses.

Benefits of Using Visual Studio
Using Visual Studio to set up rate limiting provides a streamlined and integrated environment where you can.

  • Write and test code with built-in debugging tools.
  • Quickly add or manage dependencies through the NuGet Package Manager.
  • Leverage IntelliSense and code completion for error-free implementation.

Conclusion
Rate limiting is essential for building robust, secure, and scalable APIs. By using .NET’s built-in Rate Limiting Middleware and Visual Studio’s powerful tools, you can implement and test rate-limiting policies efficiently. This ensures your application is protected, performs well, and provides a fair experience for all users. Try out these steps in your project, and ensure your APIs are ready for real-world usage.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: Encrypt and Decrypt Web.config Using aspnet_regiis.exe Tool

clock February 11, 2025 07:02 by author Peter

Using aspnet_regiis.exe tool to Encrypt and Decrypt Web.config Sections


Prerequisite (Deployment Server)

  • Locate the Framework Folder in the IIS Server, Ex: C:\Windows\Microsoft.NET\Framework{xx}\ v4.0.xxxxx OR v2.0.xxxxx.
  • Run the command prompt as Administrator Access,


Note. This tool (aspnet_regiis.exe) is typically found in the .NET Framework directory:

  • C:\Windows\Microsoft.NET\Framework\v4.0.xxxxx\aspnet_regiis.exe
  • C:\Windows\Microsoft.NET\Framework64\v4.0.xxxxx\aspnet_regiis.exe (for 64-bit)


Prerequisite (Local Development Machine)
Run the Developer Command Prompt for VS 20xx as Administrator Access

Commands to Execute

To Encrypt Section
> aspnet_regiis.exe -pef “<Section Name>” “<Physical Path located the Config File>”

To Decrypt Section
> aspnet_regiis.exe -pdf “<Section Name>” “<Physical Path located the Config File>”

Note
Encrypt or Decrypt Configuration Sections
    -pef <section> <physicalPath> → Encrypts a specific configuration section.

Example: aspnet_regiis -pef "appSettings" "C:\MyApp"

    -pdf <section> <physicalPath> → Decrypts a specific configuration section.

Example: aspnet_regiis -pdf " appSettings" "C:\MyApp"



European ASP.NET Core 9.0 Hosting - HostForLIFE :: Semi Auto Implemented Properties in .NET 9

clock February 7, 2025 07:59 by author Peter

C#13's Preview functionality is now semi-auto-implemented Properties. When specifying properties in class files, this feature greatly improves readability and cuts down on boilerplate code. Let's examine one straightforward situation to gain a better understanding.


Situation
Typically, an auto-implemented property is declared in C#.
public int EmplSalary { get; set; }

The compiler automatically generates a backing field like (Ex: _empSalary) and internal getter/setter methods (void set_EmplSalary(int empSalary) and int get_EmplSalary()).
However, In our real-time project cases, we need to set some custom logic such as validation, default values, computations, or lazy loading in the property’s getter or setter, we typically need to manually define the backing field.

C# 13 preview

This process is simplified by the introduction of the field keyword, which allows direct access to the backing field without the need for manual definition, as this feature is currently in the Preview stage. We have to apply the following keyword to use this in our project settings. Edit the project file by adding <LangVersion>preview</LangVersion>. So, It supports field property in project usage.

The following code gives a more illustrative idea about usage.

Before .NET 9

private int _empSalary;

/// <summary>
/// Before .NET 9
/// </summary>
public int EmpSalary
{
    get => _empSalary;
    set
    {
        if (value <= 0)
            throw new ArgumentOutOfRangeException(nameof(value),
                "Salary must be greater than 0");
        _empSalary = value;
    }
}


.NET 9 (Preview)
/// <summary>
/// In .NET 9
/// </summary>
public int EmployeeSalary
{
    get => field;
    set
    {
        if (value <= 0)
            throw new ArgumentOutOfRangeException(nameof(value),
                "Salary must be greater than 0");
        field = value;
    }
}


Benefits

  • Less Boilerplate Code: Removes the necessity for private backing fields, leading to more streamlined and concise code.
  • Enhanced Readability: Eliminates concerns about naming backing fields, as the standardized field keyword improves code clarity.
  • Property-Scoped Field: The private property field is accessible only within the property itself, ensuring better encapsulation and preventing unintended access elsewhere in the parent class. This key feature of C# 13 Semi-Auto Properties effectively mitigates a common source of errors.

Please also read Understanding UUID v7 in .NET 9 for other .NET9 related features.

Summary
This feature helps in our project's day-to-day scenarios with the benefits of Less Boilerplate Code, Enhanced Readability, and Property-Scoped Fields. As this feature is still in Preview mode, please use it with caution in our real-time projects.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: Use the Authorization Option to Implement Scalar UI in.NET APIs

clock February 4, 2025 06:13 by author Peter

Microsoft declared that they would no longer include the default Swagger gen UI with any.NET API project after the release of.NET 9. In the past, Microsoft incorporated the Swagger Swashbuckle package automatically when we established a.NET API project. This package had methods like apps.UseSwagger() and app.UseSwaggerUI(). Without the need for third-party apps like Postman, these techniques demonstrated API documentation with a preset user interface for testing straight in the browser. Nevertheless,.NET 9 web API projects no longer integrate Swagger. The package hasn't been properly maintained lately, and a lot of user-reported problems are still unfixed, hence this choice was made.

Microsoft.AspNetCore is a new package developed by the Microsoft team.Similar to Swagger, OpenApi offers integrated OpenAPI documentation production. Nevertheless, this just offers JSON documentation for all endpoints and schema definitions; the browser does not display any user interface. This change's primary objective is to enable customers to utilize any UI library they choose, be it Swagger or another option. You may still add Swagger to your project and carry out all of the same tasks as before, even though Microsoft removed the default package.

Although there are a lot of Swagger substitutes out there right now, we'll talk about and use Scalar in our API project in this post. Scalar has gained popularity among developers after Swagger.

Starting a New Project

You will be prompted to configure OpenAPI support when you create new projects with.NET 9. This checkbox will register the OpenAPI service in the program and add the Microsoft.AspNetCore.OpenApi package to your project.such a cs file.

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}

Now, when you run your API and navigate to /OpenApi/v1.json, it will show the documentation generated by default, which contains information about your endpoints and all the schemas you have used, as shown in the image below.

Configure Scalar.NET
First, open your package manager and install Scalar.AspNetCore.

Then, just add the app.MapScalarApiReference(); in your program.cs file to map all the API references and routes of Scalar UI. Now, if you go to /Scalar/V1, you will see a beautiful UI for your endpoints. Here, I only have one endpoint, so it looks like this.

Configure Options of Scalar
You can configure multiple options and change the settings of your UI. Some configurations include.

  • Title: Set the document title which shows on top of the browser tab
  • DarkMode: true/false to enable and disable dark mode
  • Favicon: Set the favicon of the document
  • DefaultHttpClient: Show the default HTTP client when UI loads in the browser. It shows the code implementation for the respective programming language.
  • HideModels: true/false to set whether to show model definitions
  • Layout: Set the layout/theme of Scalar UI
  • ShowSidebar: true/false to set whether to show sidebar. This only works when you have chosen the modern layout.

And many more.

Open Scalar UI by Default

You might have noticed that we have to type scalar/v1 every time in the URL to see the Scalar UI. We can change the launch URL so we don't have to do this repeatedly. Open the launchsettings.json file and add the launch URL to your profile. I have added it for both HTTP and HTTPS. You can configure it as per your requirements.

Working with Authorization and JWT Token
In most APIs, we implement JWT tokens or other types of token authentication. So, I have added a few lines of code to implement authorization using the JWT token. I have also installed Microsoft.AspNetCore.Authentication.JwtBearer package for this.
builder.Services
    .AddAuthorization()
    .AddAuthentication(x =>
    {
        x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(x =>
    {
        x.RequireHttpsMetadata = false;
        x.SaveToken = true;
        x.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = false,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("your_jwt_key")),
            ValidateIssuer = false,
            ValidateAudience = false
        };
    });

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

app.MapGet("/test1", () => "This is test 1 endpoint")
    .WithName("Test1")
    .RequireAuthorization();


When I call this test1 endpoint, it gives me a 401 error (unauthorized). So, how can we resolve this? We can simply pass an auth token, but if you look at Scalar, there's no option to add an auth/bearer token on their UI. There's no option for Auth type even if I have added PreferredSecurityScheme as Bearer in MapScalarApiReference.
options.Authentication = new ScalarAuthenticationOptions
{
    PreferredSecurityScheme = "Bearer"
};


If you pass your auth token in headers with the Authorization key, it works, but that's not what we want, right? We want a similar interface to Swagger, which shows options to add tokens on the home page or in individual endpoints.

However, there is a way to achieve what we want and resolve this issue. We can use the functionality of document transformers in OpenAPI

Using this Transformer, we can inform Scalar that we want to show the Authentication option on our UI so that Scalar can add it on the home page and also in individual endpoints.

Here's the transformer class.
internal sealed class BearerSecuritySchemeTransformer : IOpenApiDocumentTransformer
{
    private readonly IAuthenticationSchemeProvider _authenticationSchemeProvider;

    public BearerSecuritySchemeTransformer(IAuthenticationSchemeProvider authenticationSchemeProvider)
    {
        _authenticationSchemeProvider = authenticationSchemeProvider;
    }

    public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken)
    {
        var authenticationSchemes = await _authenticationSchemeProvider.GetAllSchemesAsync();

        if (authenticationSchemes.Any(authScheme => authScheme.Name == "Bearer"))
        {
            var requirements = new Dictionary<string, OpenApiSecurityScheme>
            {
                ["Bearer"] = new OpenApiSecurityScheme
                {
                    Type = SecuritySchemeType.Http,
                    Scheme = "bearer",
                    In = ParameterLocation.Header,
                    BearerFormat = "JWT"
                }
            };

            document.Components ??= new OpenApiComponents();
            document.Components.SecuritySchemes = requirements;

            foreach (var operation in document.Paths.Values.SelectMany(path => path.Operations))
            {
                operation.Value.Security.Add(new OpenApiSecurityRequirement
                {
                    [new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference
                        {
                            Id = "Bearer",
                            Type = ReferenceType.SecurityScheme
                        }
                    }] = Array.Empty<string>()
                });
            }
        }
    }
}

This code will add an Authentication option on the Home page and in all request endpoints where you can pass your token to send requests.

 

This code modifies OpenAPI/Scalar documentation to show that the API supports Bearer token authentication.

  • It first checks if the API has "Bearer" authentication enabled
  • If Bearer authentication exists, it adds a security scheme in OpenAPI/Scalar
  • This security scheme tells OpenAPI/Scalar that requests should include a JWT (JSON Web Token) in the Authorization header
  • By default, this only adds support for authentication but does not require it in OpenAPI/Scalar UI
  • To make authentication look required in the UI, the code loops through all API endpoints and marks them as needing a Bearer token

 

The following loop does that,
foreach (var operation in document.Paths.Values.SelectMany(path => path.Operations))
{
    operation.Value.Security.Add(new OpenApiSecurityRequirement
    {
        [new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference
            {
                Id = "Bearer",
                Type = ReferenceType.SecurityScheme
            }
        }] = Array.Empty<string>()
    });
}

This only affects the OpenAPI/Scalar UI and does not actually enforce authentication in the API. Even if the UI shows authentication as required, the API will still accept requests without a token unless it has [Authorize] or RequireAuthorization().

To apply this transformation in OpenAPI/Scalar, use the following line.
builder.Services.AddOpenApi(options =>
{
    options.AddDocumentTransformer<BearerSecuritySchemeTransformer>();
});

This ensures the security scheme and requirements are added whenever OpenAPI/Scalar documentation is generated. If you want to actually enforce authentication, you need to add [Authorize] to controllers or RequireAuthorization() in Minimal API. Now you can pass your token in this input, and it will be passed to the server without any issue, and you won't get a 401 error anymore.


I hope you like this article. If you have any questions, you can ask them in the comments, and don't forget to like and follow.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in