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 Hosting - HostForLIFE :: Apps for.NET 9 Run Faster Than Before

clock April 21, 2025 08:49 by author Peter

Microsoft continues to push the limits of what can be done with.NET with every new release, and.NET 9 is no exception. From quicker APIs, serialization, and more effective JIT compilation to better memory management, this most recent version offers observable performance gains across the board. This post will examine the main performance improvements in.NET 9, contrast the actual code execution of.NET 8 and.NET 9, and demonstrate how upgrading to.NET 9 can significantly improve your apps with little modification.

What's New in .NET 9 Performance?

  • Some standout performance improvements in .NET 9.
  • Improved JIT Compiler (RyuJIT)
  • Reduced GC (Garbage Collection) Pauses
  • Faster System.Text.Json Serialization/Deserialization
  • Enhanced HTTP/3 and Kestrel Web Server
  • More Efficient Task and Thread Management

Real Programming Comparison: .NET 8 vs .NET 9
Let's take a real example that most applications deal with — JSON serialization and HTTP response via Minimal APIs.

Example. Minimal API returning JSON data
Code (Same for .NET 8 and .NET 9)
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/data", () =>
{
    var data = Enumerable.Range(1, 1000)
        .Select(x => new { Id = x, Name = $"Item {x}" });
    return Results.Ok(data);
});

app.Run();


We’ll test this endpoint using a load test tool (e.g., wrk or Apache Benchmark) to compare .NET 8 and .NET 9.

Benchmark Result

Environment

  • OS: Windows 11 / Ubuntu 22.04
  • Load Test: 100,000 requests / 10 concurrent threads
Metric .NET 8 .NET 9 Improvement
Requests/sec 29,200 34,500 +18%
Avg Response Time 12.4 ms 9.8 ms -21%
Memory Allocations 2.5 MB 1.8 MB -28%
CPU Usage (under load) High Reduced  

Another Example: String Parsing Function
Let’s compare a simple string parsing function using BenchmarkDotNet.

Code
public class TextProcessor
{
    public static List<string> ExtractWords(string sentence)
    {
        return sentence
            .Split([' ', ',', '.', '!'], StringSplitOptions.RemoveEmptyEntries)
            .Where(word => word.Length > 3)
            .ToList();
    }
}


Benchmark Test
[MemoryDiagnoser]
public class BenchmarkTest
{
    private readonly string sentence = "The quick brown fox jumps over the lazy dog. Testing .NET performance!";

    [Benchmark]
    public List<string> RunTest() => TextProcessor.ExtractWords(sentence);
}

Benchmark Result

Runtime Mean Time Allocated Memory
.NET 8 5.10 µs 1.65 KB
.NET 9 4.01 µs 1.32 KB

Result: .NET 9 is ~21% faster and uses ~20% less memory.

System.Text.Json Serialization Comparison

Code

var person = new { Name = "Peter", Age = 30 };
string json = JsonSerializer.Serialize(person);
Framework Serialization Time Memory Allocation
.NET 8 2.4 µs 560 B
.NET 9 1.9 µs 424 B

.NET 9 improves System.Text.Json serialization speed and lowers memory usage for large object graphs.

Conclusion
.NET 9 is a performance beast. With smarter memory handling, improved JIT, and optimizations to HTTP servers, JSON serialization, and general computation — your apps will run faster and leaner by default. No major code changes are needed — just upgrade and reap the benefits. Whether you're building APIs, desktop apps, or microservices, .NET 9 is built to scale faster, respond quicker, and consume fewer resources. Now is the time to upgrade and experience the performance leap.

Upgrade to .NET 9 and unleash the true speed of your apps!

HostForLIFE ASP.NET Core Hosting

European Best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



European ASP.NET Core Hosting - HostForLIFE :: Discover how to integrate Firebase with .NET

clock April 14, 2025 07:19 by author Peter

A free database is provided by a Firebase database connection.  In essence, we are able to perform CRUD tasks, which include Insert, Update, Get, and Delete.  I've broken out how to install and create a project on the Firebase console panel here.  Opening Firebase and logging into your account is the first step.  The second step is to select the terminal application that opens Dashboard, click Create Project, and then enter the name of your project.

 

Making a real-time database is the third phase. Then select the test mode and press the "enable" button. You can now use this configuration for crude operations as your database has been built. The first step is to register for a Firebase account. I've included a link that will assist you in using the Firebase console app to create a project.

These are some steps listed below that take you to the exact place of Firebase integration with .NET. Firstly, you need to create a .net project and then install the NuGet package; and name of the package is FireSharp, and the version of the package is 2.0.4.

Now, you will need credentials to perform the CRUD operation.

To connect with your real-time database, copy the base path from the console app.

Then we need the authsecret key, that key you can fetch from the project setting > service account > database secret key.


Lastly, let’s write code in .NET.
// Firebase configuration
IFirebaseConfig ifc = new FirebaseConfig()
{
    AuthSecret = "**********x8Ed6HVU0YXlXW-L75ho4ps",
    BasePath = "https://we****.firebaseio.com/"
};

IFirebaseClient client;

// Create a user object
User user = new User()
{
    Id = 1,
    FirstName = "Test 1",
    LastName = "Test 2"
};

// Initialize Firebase client
client = new FireSharp.FirebaseClient(ifc);

// Insert data
var set = client.Set("User/" + user.Id, user);

// Delete data
set = client.Delete("User/" + user.Id);

// Update data
set = client.Update("User/" + user.Id, user);

// Retrieve data
set = client.Get("User/" + user.Id);


To explore more classes, please visit the official doc of Firebase Admin .NET SDK: firebase.google.com/docs/reference/admin/dotnet



European ASP.NET Core Hosting - HostForLIFE :: Creating Custom Components in Blazor

clock April 11, 2025 09:33 by author Peter

Microsoft created the open-source Blazor web framework, which enables programmers to create interactive online apps with C# and.NET. Blazor builds modular and reusable user interface components using a component-based architecture. Building intricate and reusable web apps requires the use of custom components. We will use examples to demonstrate how to develop custom components in Blazor in this article.

Prerequisites
Before we begin, ensure you have the following set up on your development environment:

  • Visual Studio 2022.
  • Basic knowledge of C# and HTML.

Understanding Components in Blazor
Components in Blazor are similar to user controls in other web frameworks. They are self-contained pieces of code that contain both markup and logic. Components can be composed and nested to create complex UI elements. In Blazor, components can be created using Razor syntax or using C# code. There are two types of components in Blazor:

  • Razor Components: These are defined using Razor syntax (.razor files) and allow for a mix of HTML and C# code.
  • Code-Behind Components: These are defined using C# classes and are more suitable for more complex logic or when you want to separate the UI and C# code.

In this article, we'll focus on creating custom Razor components.

Step 1. Create a New Blazor Project
Let's start by creating a new Blazor project. Open Visual Studio and follow these steps:

  • Click on "Create a new project."
  • In the "Create a new project" dialog, search for "Blazor WebAssembly App," select the "Blazor WebAssembly App" template and click on "Next".
  • Choose a name and location for your project, and click "Next".
  • Choose the ".NET 7.0" option from the framework and click "Create" to generate the project.

Step 2. Add a Custom Component
In this example, we'll create a simple custom component that displays a welcome message with the ability to customize the name.

  • Right-click on the "Pages" folder in your Blazor project, and select "Add" > "New Folder." Name the folder "Components."
  • Right-click on the newly created "Components" folder, and select "Add" > "New Item."
  • In the "Add New Item" dialog, search for "Razor Component" and select the "Razor Component" template.
  • Name the component "WelcomeMessage.razor" and click "Add."

Step 3. Define the Custom Component
Now, let's define the content of our custom component. Open the "WelcomeMessage.razor" file and replace its content with the following code.
@code {
    [Parameter] public string Name { get; set; } = "Guest";
}
<h3>Welcome, @Name!</h3>

In this code, we have a simple Razor component with a parameter named "Name." The parameter represents the name of the user to display in the welcome message. We've set a default value of "Guest" in case the name is not provided.

Step 4. Using the Custom Component

Now that we have our custom component defined let's use it in one of our existing Blazor pages. Open the "Index.razor" file located in the "Pages" folder and add the following line at the top of the file to import the "WelcomeMessage" component.
@page "/"

@using YourAppName.Components


Next, add the following code within the existing <div> tag in the "Index.razor" file:
<WelcomeMessage Name="Peter" />

This line of code will render the "WelcomeMessage" component with the name "Peter".

Step 5. Build and Run the Application

With the custom component in place, we can now build and run the application to see it in action. Press Ctrl + F5 or click the "Start Debugging" button in Visual Studio to build and run the application.
Once the application loads in your browser, you should see the welcome message, "Welcome, Peter!" If you don't see the name, check if you've correctly implemented the custom component.

How to Create Reusable Components?
One of the main benefits of using custom components in Blazor is the ability to create reusable UI elements. To create a reusable component, you can define it in a separate file and import it into other components as needed. Here's an example of a reusable component that displays a button.

Create a new component named as SubmitButton and add the below code.
<button class="@ButtonClass" @onclick="OnClick">@ButtonText</button>

@code {
    [Parameter]
    public string ButtonText { get; set; } = "Button";

    [Parameter]
    public string ButtonClass { get; set; } = "btn-primary";

    [Parameter]
    public EventCallback<MouseEventArgs> OnClick { get; set; }
}


This component takes three parameters: the button text, the button class, and a callback that is triggered when the button is clicked. The default values for the button text and class are set in the component, but they can be overridden when the component is used.

To use this component in your application, you can add the following code to a Razor page.
<SubmitButton ButtonText="Click Me" ButtonClass="btn-success" OnClick="HandleClick" />
@code {
    private async Task HandleClick(MouseEventArgs args)
    {
        // Handle the button click event
    }
}


This will render a button with the text "Click Me" and the class "btn-success". When the button is clicked, the HandleClick method will be called.

Conclusion

Custom components are a powerful feature of Blazor that allow developers to create reusable and modular UI elements. By creating custom components, developers can build complex web applications more efficiently and with greater flexibility. In this article, we explored how to create custom components in Blazor using examples. We hope this article has been helpful in understanding how to create custom components in Blazor.

HostForLIFE ASP.NET Core Hosting

European Best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



European ASP.NET Core Hosting - HostForLIFE :: ASP.NET Core Advanced APIs: Versioning, EF Core, and Middleware

clock April 7, 2025 10:15 by author Peter

My preferred framework for creating scalable web services is ASP.NET Core Web API. When creating scalable web services, I like to use the ASP.NET Core Web API. I can't wait to tell you about it. Using Entity Framework Core, Dependency Injection, API versioning, and a little extra code to log requests and responses, I'll walk you through how I created it in this tutorial.

We're looking at sophisticated concepts for developing APIs that expand as your program gets larger, so this won't be your typical beginner's assignment. Let's get started.

Step 1. Setting Up the Project
First, I fired up Visual Studio and created a new ASP.NET Core Web API project. Here’s how I did it.

  • Open Visual Studio and click on Create a new project.
  • I chose ASP.NET Core Web API and clicked Next.
  • Named the project EmployeeManagementAPI—you can name it whatever you like—and clicked Create.
  • I selected .NET 7.0 and hit Create.

Once Visual Studio had set up the basic project structure, I was ready to roll. Next, it was time to integrate Entity Framework Core so I could store and manage employee data in a database.

Step 2. Integrating Entity Framework Core

I needed to hook up a database to store employee records. For this, I went with Entity Framework Core because it’s super flexible and easy to work with.

Installing EF Core

First things first, I installed the required packages via Package Manager Console.
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools


With that out of the way, I moved on to creating a DbContext to represent the database. I created a folder called Data and added a new class called EmployeeContext. Here’s the code I put in.
using Microsoft.EntityFrameworkCore;
using EmployeeManagementAPI.Models;

namespace EmployeeManagementAPI.Data
{
    public class EmployeeContext : DbContext
    {
        public EmployeeContext(DbContextOptions<EmployeeContext> options)
            : base(options)
        {
        }

        public DbSet<Employee> Employees { get; set; }
    }
}


Next, I needed an Employee model. In the Models folder, I added the Employee.cs class.
namespace EmployeeManagementAPI.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Department { get; set; }
        public decimal Salary { get; set; }
    }
}


Configuring the Database Connection
With the DbContext and model in place, I needed to configure the connection string. I added the connection string in appsettings.json like this.

"ConnectionStrings": {
  "EmployeeConnection": "Server=(localdb)\\mssqllocaldb;Database=EmployeeManagementDB;Trusted_Connection=True;"
}

Then, in Program.cs, I added the following line to register EmployeeContext with Dependency Injection.

builder.Services.AddDbContext<EmployeeContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("EmployeeConnection")));


Running Migrations
Finally, I created the database using EF Core migrations. Here’s what I did.

  • Add-Migration InitialCreate
  • Update-Database

This created the Employees table in the database. With the database ready, it was time to move on to the service layer.

Step 3. Building the Service Layer
Rather than dumping all the logic into the controller, I created a service layer to handle employee operations. This helps keep the code cleaner and easier to maintain.
Creating the Service Interface and Implementation

In the Services folder, I added an interface, IEmployeeService, and its implementation, EmployeeService. Here's what I came up with,

First, the interface.

public interface IEmployeeService
{
    Task<IEnumerable<Employee>> GetAllEmployeesAsync();
    Task<Employee> GetEmployeeByIdAsync(int id);
    Task AddEmployeeAsync(Employee employee);
    Task UpdateEmployeeAsync(Employee employee);
    Task DeleteEmployeeAsync(int id);
}


Then, I implemented the interface in EmployeeService.cs.

public class EmployeeService : IEmployeeService
{
    private readonly EmployeeContext _context;

    public EmployeeService(EmployeeContext context)
    {
        _context = context;
    }

    public async Task<IEnumerable<Employee>> GetAllEmployeesAsync()
    {
        return await _context.Employees.ToListAsync();
    }

    public async Task<Employee> GetEmployeeByIdAsync(int id)
    {
        return await _context.Employees.FindAsync(id);
    }

    public async Task AddEmployeeAsync(Employee employee)
    {
        _context.Employees.Add(employee);
        await _context.SaveChangesAsync();
    }

    public async Task UpdateEmployeeAsync(Employee employee)
    {
        _context.Entry(employee).State = EntityState.Modified;
        await _context.SaveChangesAsync();
    }

    public async Task DeleteEmployeeAsync(int id)
    {
        var employee = await _context.Employees.FindAsync(id);
        if (employee != null)
        {
            _context.Employees.Remove(employee);
            await _context.SaveChangesAsync();
        }
    }
}


Now, I needed to register this service in Program.cs so it could be injected into the controllers.

builder.Services.AddScoped<IEmployeeService, EmployeeService>();


Step 4. Building the Employee Controller
With the service layer ready, I moved on to the controller. In the Controllers folder, I created EmployeesController.cs.

[Route("api/[controller]")]
[ApiController]
public class EmployeesController : ControllerBase
{
    private readonly IEmployeeService _employeeService;

    public EmployeesController(IEmployeeService employeeService)
    {
        _employeeService = employeeService;
    }

    [HttpGet]
    public async Task<IActionResult> GetAllEmployees()
    {
        var employees = await _employeeService.GetAllEmployeesAsync();
        return Ok(employees);
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetEmployeeById(int id)
    {
        var employee = await _employeeService.GetEmployeeByIdAsync(id);
        if (employee == null)
        {
            return NotFound();
        }
        return Ok(employee);
    }

    [HttpPost]
    public async Task<IActionResult> AddEmployee([FromBody] Employee employee)
    {
        await _employeeService.AddEmployeeAsync(employee);
        return CreatedAtAction(nameof(GetEmployeeById), new { id = employee.Id }, employee);
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> UpdateEmployee(int id, [FromBody] Employee employee)
    {
        if (id != employee.Id)
        {
            return BadRequest();
        }
        await _employeeService.UpdateEmployeeAsync(employee);
        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteEmployee(int id)
    {
        await _employeeService.DeleteEmployeeAsync(id);
        return NoContent();
    }
}


This controller was straightforward and tied everything together. I now had a fully functional API for managing employees.

Step 5. Adding API Versioning
As the API grew, I knew I’d need to implement API versioning to ensure backward compatibility. I installed the versioning package.
Install-Package Microsoft.AspNetCore.Mvc.Versioning


Next, I configured versioning in Program.cs.
builder.Services.AddApiVersioning(options =>
{
    options.AssumeDefaultVersionWhenUnspecified = true;
    options.DefaultApiVersion = new ApiVersion(1, 0);
    options.ReportApiVersions = true;
});


Now, I could version my controllers like this.

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class EmployeesV1Controller : ControllerBase
{
    // Version 1.0 controller code
}


Step 6. Custom Middleware for Logging
One thing I always like to do is log requests and responses, especially when working with APIs. So, I wrote some custom middleware to log incoming requests and outgoing responses.

Here’s what my middleware looked like.

public class RequestLoggingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<RequestLoggingMiddleware> _logger;

    public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        _logger.LogInformation($"Incoming request: {context.Request.Method} {context.Request.Path}");
        await _next(context);
        _logger.LogInformation($"Outgoing response: {context.Response.StatusCode}");
    }
}


Then, I registered this middleware in Program.cs.
app.UseMiddleware<RequestLoggingMiddleware>();

Now, every request and response was being logged, which made debugging much easier.

Conclusion

And there you have it—an advanced Employee Management API built with ASP.NET Core Web API. We covered a lot of ground, from integrating Entity Framework Core to creating a solid service layer, and even added some extra touches like API versioning and custom middleware.

This is the kind of architecture that scales well and keeps things organized. If you’ve made it this far, your API is in great shape for future growth.

Next Steps

  • Consider adding authentication and authorization to secure the API (I recommend using JWT).
  • Look into caching to improve performance, especially for frequently accessed data.
  • Write unit tests for your services and controllers to ensure your API behaves as expected.

Happy coding!

HostForLIFE ASP.NET Core Hosting

European Best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in