Tuesday, 8 July 2025

Examining.NET 9: What Developers Can Expect

Leave a Comment

The foundation of contemporary enterprise and cloud-native development is still.NET. Microsoft is launching strong new features with.NET 9 that should improve cross-platform compatibility, developer productivity, and performance.

 

We'll examine some of the most intriguing new features and enhancements with.NET 9 in this post.

1. Native AOT Improvements

Native AOT (Ahead-Of-Time Compilation) is getting more mature and usable for production workloads. .NET 9 delivers.

  • Smaller executable sizes.
  • Faster startup times.
  • Lower memory footprint.

If you’re building microservices or serverless functions, Native AOT can dramatically reduce cold start latency.

2. ASP.NET Core Enhancements

ASP.NET Core in .NET 9 adds.

  • Improved minimal APIs, including better request handling and model binding.
  • Enhanced Blazor features enable richer interactivity and support hybrid scenarios.
  • Performance optimizations that further reduce overhead and improve throughput.

These enhancements make it easier than ever to build high-performance web apps.

3. Improved Performance Across the Stack

Each .NET release continues to raise the bar.

  • Faster JIT compilation.
  • More efficient garbage collection.
  • Optimizations for LINQ and collections.

For compute-intensive workloads, you’ll see measurable improvements right out of the box.

4. AI Integration

.NET 9 is aligning closely with AI workloads.

  • Improved ML.NET integration.
  • Better support for running ONNX models.
  • Simpler ways to bring machine learning into your applications.

Expect more tooling and libraries that enable intelligent apps.

5. C# 13 Language Features

C# 13 (shipping alongside .NET 9) introduces new capabilities.

  • Enhanced pattern matching.
  • Improved interpolated string handlers.
  • Simplified async streams.

These features make your code more expressive and maintainable.

6. Enhanced Cross-Platform Development

.NET 9 reinforces its cross-platform promise.

  • Better Linux support.
  • Simplified containerization with minimal base images.
  • Consistent behavior across Windows, Linux, and macOS.

Whether you target cloud, desktop, or mobile, .NET 9 continues to unify the platform story.

Why Upgrade?

If you’re running on .NET 6 or .NET 7, upgrading to .NET 9 can give you.

  • Faster performance
  • Reduced infrastructure costs
  • New language features
  • Long-term support (LTS release)

Best ASP.NET Core 10.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFEASP.NET, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up. 

https://hostforlifeasp.net/ 

Read More...

Tuesday, 1 July 2025

ASP.NET Dependency Injection for Novices

Leave a Comment

Dependency Injection: What is it?
Let's say you have an automobile that requires an engine to function. You deliver (inject) the engine to the car from the outside rather than having it manufacture its own. In this manner, the car only cares if the engine runs, not how it is constructed.


In terms of programming,

To function, a class (like your car) requires another class (like the engine).
You inject the dependency (engine) from the outside rather than having the class create it.

We refer to this as Dependency Injection.

There are 3 Types of DI.

  • Constructor Injection
  • Property Injection
  • Method Injection

Real-World Scenario: Notification System

Step 1. Define Interfaces.


Step 2.
Implement the Interfaces.


 Step 3. Create the Service Class (Uses All 3 DI Types).


Step 4.
Use the Service in a Real-World Scenario (such as in a Console or ASP.NET application).

 

Best ASP.NET Core 10.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFEASP.NET, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

Read More...

Sunday, 22 June 2025

Are You Looking for The Best Joomla 5.3.0 Hosting in UK?

Leave a Comment
To choose the Joomla 5.3.0 Hosting in UK for your site, we recommend you going with the following Best & Cheap Joomla 5.3.0 Hosting company that are proved reliable and sure by our editors. Meet Joomla 5.3.0 , a powerful new suite of tools, and the strongest link in your new content supply chain. Interact with countless applications, thanks to REST-first native web services. Use progressive decoupling to break free from back-end restrictions without sacrificing security and accessibility. Deliver faster, with enhanced entity caching and better integration with CDNs and reverse proxies. With Joomla 5.3.0 , you can build almost any integrated experience you can imagine.
 

Are You Looking for The Best Joomla 5.3.0  Hosting in UK?

UKWindowsHostASP.NET review is based on their industry reputation, web hosting features, performance, reliability, customer service and price, coming from our real hosting experience with them and the approximately 100 reviews from their real customers.UKWindowsHostASP.NET offers a variety of cheap and affordable UK Joomla 5.3.0 Hosting Plans with unlimited disk space for your website hosting needs.

UKWindowsHostASP.NET revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Some other hosting providers manually execute configuration requests, which can take days. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to UKWindowsHostASP.NET's customers.
https://ukwindowshostasp.net/UK-Joomla-Web-Hosting

UKWindowsHostASP.NET is the best UK Windows Hosting provider that offers the most affordable world class windows hosting solutions for their customers. They provide shared, reseller, cloud, and dedicated web hosting. They currently operate servers in four prestiguous cities in Europe, namely: London (UK), Amsterdam (Netherlands), Frankfurt (Germany), Washington DC (US), Paris (France), Singapore and Chennai (India). Their target is to provide a versatile and dependable one-stop online hosting and marketing shop for the small business entrepreneur, and eliminate the need for you to deal with a host of different online vendors. They offer high quality web hosting, dedicated servers, web design, domain name registration, and online marketing to help lead your business to online success.

Leveraging a strong market position within the domain name registration industry, UKWindowsHostASP.NET has carefully nurtured relationships with its customer base and built a feature-rich line of value-added services around its core domain name product offering. By bundling services and providing one-stop shopping, UKWindowsHostASP.NET has successfully grown and enjoyed increased breadth and loyalty of its customer base. 

The Reason Why Choosing UKWindowsHostASP.NET?

  • 24/7-based Support -They never fall asleep and they run a service that is operating 24/7 a year. Even everyone is on holiday during Easter or Christmas/New Year, they are always behind their desk serving their customers.
  • Excellent Uptime Rate - Their key strength in delivering the service to you is to maintain their server uptime rate. They never ever happy to see your site goes down and they truly understand that it will hurt your onlines business.
  • High Performance and Reliable Server - They never ever overload their server with tons of clients. They always load balance their server to make sure they can deliver an excellent service, coupling with the high performance and reliable server.
  • Experts in Web Hosting - Given the scale of their environment, they have recruited and developed some of the best talent in the hosting technology that you are using.
  • Daily Backup Service - They realise that your website is very important to your business and hence, they never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive.
  • Easy Site Administration - With their powerful control panel, you can always administer most of your site features easily without even needing to contact for their Support Team.
Read More...

Tuesday, 17 June 2025

API Rate Limiting in .NET

Leave a Comment

Limiting the number of requests a user or client can make is crucial in the realm of online APIs, particularly public ones. We call this API Rate Limiting. In its absence, a single irresponsible or malevolent user might overwhelm your server, cause other users' services to lag, or even bring down your entire application. Let's take a closer look at this idea, see how it functions in.NET, and examine some best practices, actual cases, and even interview questions that may be useful.

What is API Rate Limiting?

Simply put, Rate Limiting controls how often someone (like a user, client, or IP address) can make requests to an API within a specific period.

For example

  • A public API may allow 100 requests per minute per user.
  • If someone sends 101 requests, the 101st will be rejected or delayed.

This protects the backend and ensures fair usage by all clients.

Why Do We Need API Rate Limiting?
  1. Avoid Server Overload: Prevents your server from crashing due to too many requests.
  2. Stops Abuse: Blocks bots or malicious users from hammering your API.
  3. Ensures Fair Usage: All users get a fair share of the service.
  4. Reduces Cost: If you're using cloud services (like Azure/AWS), more requests mean more cost.
  5. Enhances Security: Prevents brute-force attacks, especially on login APIs.
API Rate Limiting in .NET

.NET provides simple and flexible ways to implement rate limiting, especially since .NET 7 and .NET 8, where a built-in Rate Limiting Middleware was introduced.

Setting Up Rate Limiting in ASP.NET Core 8

You can add rate limiting using the built-in AspNetCore.RateLimiting package.

1. Install NuGet Package (if required)

dotnet add package AspNetCoreRateLimit

2. Configure in Program.cs

builder.Services.AddMemoryCache();
builder.Services.Configure<IpRateLimitOptions>(builder.Configuration.GetSection("IpRateLimiting"));
builder.Services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
builder.Services.AddInMemoryRateLimiting();

In appsettings.json

"IpRateLimiting": {
  "EnableEndpointRateLimiting": true,
  "StackBlockedRequests": false,
  "RealIpHeader": "X-Real-IP",
  "ClientIdHeader": "X-ClientId",
  "HttpStatusCode": 429,
  "GeneralRules": [
    {
      "Endpoint": "*",
      "Period": "1m",
      "Limit": 5
    }
  ]
}

✔️ This will limit each client to 5 requests per minute for all endpoints (*).

Alternate way

using Microsoft.AspNetCore.RateLimiting;
using System.Threading.RateLimiting;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRateLimiter(options =>
{
    options.AddFixedWindowLimiter("fixed", opt =>
    {
        opt.Window = TimeSpan.FromSeconds(10);
        opt.PermitLimit = 5; // Allow 5 requests every 10 seconds
        opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
        opt.QueueLimit = 2; // Maximum 2 requests will wait in queue
    });
});

var app = builder.Build();

app.UseRateLimiter();

app.MapGet("/", () => "Hello!").RequireRateLimiting("fixed");

app.Run();

Explanation

  • Window: Time window to measure requests.
  • PermitLimit: Number of requests allowed.
  • QueueLimit: Extra requests to wait in the queue.
  • RequireRateLimiting("fixed"): Apply this policy to specific endpoints.
Real-world Scenarios (Where Rate Limiting Helps)
  1. Public APIs like weather, currency exchange, etc.
    • Prevents free users from abusing the API.
  2. Login & Authentication endpoints
    • Stops brute-force attacks.
  3. Payment Gateway APIs
    • Limits transaction requests to avoid fraud.
  4. Microservices architecture
    • One service calling another repeatedly can exhaust system resources.
Example Use Case

Imagine a Matrimony Application API:

  • Free users: Max 20 requests/minute.
  • Premium users: Max 100 requests/minute.

This ensures premium users get faster service without being affected by free users’ heavy traffic.

How to do this?

Use user roles or JWT claims inside the limiter logic to apply different limits dynamically.

How to Handle Clients Exceeding Limits?

When a client hits the limit:

  • 429 Too Many Requests HTTP status code is returned.
  • Optionally, include a Retry-After header to inform them when they can try again.

Example response

HTTP/1.1 429 Too Many Requests
Retry-After: 30
Best Practices for API Rate Limiting
  • ✅ Set different limits for different users (e.g., free vs. paid).
  • ✅ Always log when limits are hit (for audit or debugging).
  • ✅ Notify clients properly with error codes and retry headers.
  • ✅ Use Redis or distributed caches for scalable limits across multiple servers.
  • ✅ Don't forget internal APIs or microservices calls — they may also need limits.

Common Interview Questions (with Answers)

Q 1. Why is Rate Limiting important in APIs?

A. It prevents misuse, protects backend resources, avoids server overload, and ensures fair usage among clients.

Q 2. How do you implement Rate Limiting in .NET Core?

A. Using the AspNetCore.RateLimiting middleware. Configure policies (FixedWindow, SlidingWindow, TokenBucket, Concurrency) in the Program.cs file and apply them to endpoints using .RequireRateLimiting("policyName").

Q 3. What is the difference between Fixed Window and Sliding Window rate limiting?
  • Fixed Window: Limits apply to fixed time blocks (e.g., 10 requests every minute).
  • Sliding Window: Limits apply to rolling periods — more accurate but slightly complex.
Q 4. What HTTP status code is used when a rate limit is hit?

429 Too Many Requests.

Q 5. Can Rate Limiting be role-based?

Yes. You can set different limits based on user roles, API keys, or tokens using custom resolvers or policies.

Conclusion

Rate limiting is no longer optional — it’s a must-have feature for all APIs. In .NET, adding rate limiting is now super simple thanks to the built-in middleware. Whether you’re building small internal tools or large public services, a proper rate-limiting strategy will protect your application from abuse and ensure reliability.

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

Tuesday, 10 June 2025

ASP.NET Core Multi-Tenant SaaS Applications

Leave a Comment

Building applications that effectively serve numerous clients (tenants) from a single codebase is crucial as Software-as-a-Service (SaaS) continues to rule the tech industry. With its scalable and modular design, ASP.NET Core is an effective platform for putting multi-tenant SaaS apps into practice.

This article will guide you through core principles, patterns, and a practical approach to building a multi-tenant ASP.NET Core app.

What is Multi-Tenancy?

In a multi-tenant architecture, a single application instance serves multiple tenants, with each tenant having isolated data and configurations. There are three common multi-tenancy models.

  1. Single Database, Shared Schema: All tenants share the same database and tables. Tenant data is filtered per request.
  2. Single Database, Separate Schema per Tenant: One database, but each tenant has its own schema.
  3. Separate Database per Tenant: Each tenant has a completely separate database. Most secure, but also complex.
Core Components of a Multi-Tenant ASP.NET Core App

1. Tenant Identification Middleware

You must identify the tenant from the request, commonly through.

  • Subdomain (e.g., tenant1.app.com)
  • Header (e.g., X-Tenant-ID)
  • URL path (e.g., /tenant1/dashboard)
public class TenantResolutionMiddleware
{
    private readonly RequestDelegate _next;

    public TenantResolutionMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context, ITenantService tenantService)
    {
        var tenantId = context.Request.Headers["X-Tenant-ID"].FirstOrDefault();
        if (string.IsNullOrEmpty(tenantId))
        {
            context.Response.StatusCode = 400; // Bad Request
            await context.Response.WriteAsync("Tenant ID missing.");
            return;
        }

        await tenantService.SetCurrentTenantAsync(tenantId);
        await _next(context);
    }
}

2. Tenant Context & Service

Create a scoped service to store tenant information per request.

public interface ITenantService
{
    TenantInfo CurrentTenant { get; }
    Task SetCurrentTenantAsync(string tenantId);
}

public class TenantService : ITenantService
{
    public TenantInfo CurrentTenant { get; private set; }

    public Task SetCurrentTenantAsync(string tenantId)
    {
        // Fetch tenant info from a DB or config
        CurrentTenant = new TenantInfo { Id = tenantId, Name = $"Tenant {tenantId}" };
        return Task.CompletedTask;
    }
}

3. Data Isolation Using EF Core

Use a global query filter in Entity Framework Core to isolate data.

public class AppDbContext : DbContext
{
    private readonly ITenantService _tenantService;

    public AppDbContext(DbContextOptions<AppDbContext> options, ITenantService tenantService)
        : base(options)
    {
        _tenantService = tenantService;
    }

    public DbSet<Order> Orders { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        var tenantId = _tenantService.CurrentTenant?.Id;
        modelBuilder.Entity<Order>().HasQueryFilter(o => o.TenantId == tenantId);
    }
}

Managing Per-Tenant Configuration

Store configurations like feature toggles, limits, or branding in a TenantSettings table, and cache them using a memory cache or Redis.

public class TenantInfo
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string ThemeColor { get; set; }
    public string DbConnectionString { get; set; } // for DB-per-tenant model
}
Tenant-Based Dependency Injection

ASP.NET Core allows scoped services per request; use it to register tenant-specific services dynamically if needed.

Authentication & Authorization

Use IdentityServer or JWT tokens that carry the tenant ID. This ensures that tokens are scoped to a particular tenant and can’t be used across them.

Testing and Debugging Multi-Tenant Logic
  • Use integration tests to simulate tenant-specific scenarios.
  • Enable verbose logging during tenant resolution.
  • Protect tenant boundaries using middleware and filters.

Best Practices

  • Isolate tenant data at all layers, including caching and messaging.
  • Use caching wisely, with tenant-scoped keys.
  • Implement strict authorization and rate limits per tenant.
  • Monitor and log tenant-specific performance metrics.
Conclusion

It takes more than just shared data to create a multi-tenant SaaS application in ASP.NET Core. It all comes down to tenant-aware design patterns, secure isolation, and clever architecture. You can confidently grow your SaaS application by integrating middleware, scoped services, EF Core filters, and contemporary deployment techniques.

Happy coding!

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

Tuesday, 3 June 2025

ASP.NET Core Web API Login with MongoDB

Leave a Comment

 How to use MongoDB in.NET 8 to configure logging in an ASP.NET Core Web API. This comprehensive tutorial demonstrates how to use Serilog to record logs and store them in MongoDB, which facilitates error tracking, API behavior monitoring, and real-time application activity analysis.



One of the most crucial aspects of developing a practical application is logging. It assists you in tracking faults, keeping an eye on behavior, and comprehending the background operations of your application.

In this article, you’ll learn how to,

  • Set up a Web API in ASP.NET Core (.NET 8)
  • Use Serilog for logging
  • Store logs in MongoDB
  • View logs in MongoDB Compass

We’ll keep things simple but detailed so even beginners can follow along.

Prerequisites

Make sure you have these installed.

  • .NET 8 SDK
  • MongoDB
  • MongoDB Compass (optional, for viewing logs)
  • Basic knowledge of ASP.NET Core

Step 1. Create a New ASP.NET Core Web API Project.

Open your terminal and run.

dotnet new webapi -n LoggingWithMongo
cd LoggingWithMongo

This will create a sample Web API project.

Step 2. Install Required NuGet Packages.

We’ll use Serilog to handle logging, and a MongoDB sink to write logs to MongoDB.

Run these commands.

dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.MongoDB

Step 3. Set Up Serilog in Program.cs.

Open Program.cs, and update it as follows.

1. Add the using statement.

using Serilog;

2. Configure Serilog Logging.

Add this before the builder.Build()

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .WriteTo.MongoDB(
        "mongodb://localhost:27017/logs", // MongoDB connection string
        collectionName: "logEntries",     // MongoDB collection name
        cappedMaxSizeMb: 50               // Optional: limit collection size
    )
    .Enrich.FromLogContext()
    .CreateLogger();

builder.Host.UseSerilog();

Here’s the full updated Program.cs.

using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Configure Serilog
Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .WriteTo.MongoDB(
        "mongodb://localhost:27017/logs", // Replace with your MongoDB connection string
        collectionName: "logEntries"
    )
    .Enrich.FromLogContext()
    .CreateLogger();

builder.Host.UseSerilog(); // Replace default logger

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

app.UseAuthorization();

app.MapControllers();

app.Run();

Step 4. Add Logging to a Controller.

Let’s add some logging inside the default WeatherForecastController.

Open Controllers/WeatherForecastController.cs and update it like this.

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        _logger.LogInformation("Weather forecast requested at {Time}", DateTime.UtcNow);

        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

This line.

_logger.LogInformation("Weather forecast requested at {Time}", DateTime.UtcNow);

will write a log entry each time the endpoint is called.

Step 5. Run the Application.

Use this command to start the app.

dotnet run

Now open your browser and go to,

https://localhost:5001/weatherforecast

Each time you refresh the page, a new log will be generated and saved to MongoDB.

Step 6. View Logs in MongoDB.

Open MongoDB Compass or use the Mongo shell.

In MongoDB Compass.

  • Connect to your server (mongodb://localhost:27017)
  • Open the database logs
  • Go to the logEntries collection

You’ll see documents like this.

{
  "_id": ObjectId("665d1739a92a511a28e4d341"),
  "Timestamp": "2025-06-03T14:00:00Z",
  "Level": "Information",
  "MessageTemplate": "Weather forecast requested at {Time}",
  "RenderedMessage": "Weather forecast requested at 6/3/2025 2:00:00 PM",
  "Properties": {
    "Time": "2025-06-03T14:00:00Z",
    "SourceContext": "LoggingWithMongo.Controllers.WeatherForecastController"
  }
}

You can use MongoDB queries to search, filter, or export logs.

Conclusion

Now your Web API logs are being saved in MongoDB! This is useful for,

  • Centralized log storage
  • Debugging issues
  • Monitoring app activity
  • Viewing logs from multiple servers

You can expand this by adding more structured data, custom enrichers, and log filtering.

Let me know if you’d like help adding things like,

  • Request/response logging
  • Error logging middleware
  • Logging user info or IP addresses

Happy coding!

ASP.NET Core 10.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 10.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFE.eu guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

 
Read More...

Tuesday, 27 May 2025

Comparing Two Images in .NET Core Using Bitmap

Leave a Comment

Create a.net core Console application in Visual Studio and install System.Drawing. The common library can be found in the NuGet Package Manager or the command line. In this post, we will compare two photos using the BitMap library in the dot net core application.

For the NuGet Package Manager Console, run the below command.

Install-Package System.Drawing.Common

For the .NET CLI command line, run the below command.

dotnet add package System.Drawing.Common

Basic image identification can be done with Hashing MD5 using the Cryptography library. For quick comparison generate a hash for each image and compare the image hashes and it will give the result.

Code Example

using System.Drawing;
using System.Security.Cryptography;

Console.WriteLine("Cryptography MD5 Quick Comparison ");
bool st= AreImagesIsIdentical(@"image1.PNG",@"image2.PNG");


Console.WriteLine("is Same image :" + st);
string GetImageHash(string imagePath)
{
    using (var md5 = MD5.Create())
    {
        using (var stream = new FileStream(imagePath, FileMode.Open))
        {
            var hash = md5.ComputeHash(stream);
            return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
        }
    }
}

 bool AreImagesIdentical(string imagePath1, string imagePath2)
{
    return GetImageHash(imagePath1) == GetImageHash(imagePath2);
}

Output

The bitmap library will help to compare pixels in the images. For comparing the pixel values of the two images, the code example is below.

using System.Drawing;

Console.WriteLine("Pixel Comparison ");
bool st= AreImagesIsIdentical(@"image1.PNG",@"image2.PNG");

bool AreImagesIsIdentical(string imagePath1, string imagePath2)
{
    using (Bitmap bmp1 = new Bitmap(imagePath1))
    using (Bitmap bmp2 = new Bitmap(imagePath2))
    {
        if (bmp1.Width != bmp2.Width || bmp1.Height != bmp2.Height)
        {
            return false;
        }

        for (int y = 0; y < bmp1.Height; y++)
        {
            for (int x = 0; x < bmp1.Width; x++)
            {
                if (bmp1.GetPixel(x, y) != bmp2.GetPixel(x, y))
                {
                    return false;
                }
            }
        }
    }
    return true;
}

Output

 

Best ASP.NET Core 10.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFEASP.NET, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.
Read More...