Showing posts with label asp.net core. Show all posts
Showing posts with label asp.net core. Show all posts

Thursday, January 23, 2025

Understanding Forwarded Headers Middleware in ASP.NET Core

🚀

Introduction

In modern web applications, especially those deployed behind reverse proxies (like Nginx, Apache, or cloud services like AWS and Azure), handling request headers correctly is crucial. The Forwarded Headers Middleware in ASP.NET Core ensures that proxies and load balancers pass the correct client information to the application.

This blog post will cover:
✅ What Forwarded Headers Middleware is
✅ Why it's important
✅ How to configure it in ASP.NET Core with a practical code example


🌟 What is Forwarded Headers Middleware?

When an application is deployed behind a reverse proxy, the proxy modifies request headers. For example:

  • The original client IP is replaced with the proxy server’s IP.
  • The HTTPS scheme may be removed if the proxy forwards requests via HTTP.

To ensure your app detects the correct client details, ASP.NET Core provides the Forwarded Headers Middleware.

🔹 Headers Managed by ForwardedHeadersMiddleware

1️⃣ X-Forwarded-For → Captures the original client IP.
2️⃣ X-Forwarded-Proto → Indicates the original HTTP scheme (HTTP or HTTPS).
3️⃣ X-Forwarded-Host → Contains the original host requested by the client.


🛠️ Configuring Forwarded Headers Middleware in ASP.NET Core

Let’s see how to enable and configure Forwarded Headers Middleware in an ASP.NET Core application.

1️⃣ Install Required Packages (Optional)

If not already installed, ensure the Microsoft.AspNetCore.HttpOverrides package is added:

dotnet add package Microsoft.AspNetCore.HttpOverrides

2️⃣ Configure Forwarded Headers Middleware in Program.cs

Modify your Program.cs file to include the middleware:

using Microsoft.AspNetCore.HttpOverrides;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// 🌟 Enable Forwarded Headers Middleware
var options = new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
};

// 🔹 (Optional) Allow Known Proxies
options.KnownProxies.Add(System.Net.IPAddress.Parse("192.168.1.100")); 

app.UseForwardedHeaders(options);

// Sample Endpoint to Check Headers
app.MapGet("/", (HttpContext context) =>
{
    var clientIP = context.Connection.RemoteIpAddress?.ToString();
    var originalIP = context.Request.Headers["X-Forwarded-For"].ToString();
    var originalScheme = context.Request.Headers["X-Forwarded-Proto"].ToString();

    return Results.Json(new
    {
        ClientIP = clientIP,
        ForwardedFor = originalIP,
        ForwardedProto = originalScheme
    });
});

app.Run();

🔍 Understanding the Code

🔹 ForwardedHeadersOptions → Specifies which headers to process (X-Forwarded-For, X-Forwarded-Proto).
🔹 KnownProxies → Lists trusted proxies (important for security).
🔹 UseForwardedHeaders(options) → Enables the middleware before other request-processing middleware.
🔹 HttpContext.Request.Headers → Reads the forwarded headers inside an API endpoint.


⚡ Testing Forwarded Headers in Postman or Curl

You can simulate forwarded headers using Postman or cURL:

curl -H "X-Forwarded-For: 203.0.113.42" -H "X-Forwarded-Proto: https" http://localhost:5000

✅ Expected Response (Example Output)

{
    "ClientIP": "::1",
    "ForwardedFor": "203.0.113.42",
    "ForwardedProto": "https"
}

📌 Best Practices

1️⃣ Only trust known proxies → Use KnownProxies or KnownNetworks to avoid spoofing risks.
2️⃣ Enable forwarding at the right stage → Configure before authentication middleware.
3️⃣ Use middleware only behind a proxy → Avoid unnecessary header processing in development.


🎯 Conclusion

The Forwarded Headers Middleware is essential for handling reverse proxy headers in ASP.NET Core applications. It ensures that the application correctly identifies the client IP address and scheme, improving security and logging accuracy.

🔥 Key Takeaways:
✅ Enables handling of X-Forwarded-For, X-Forwarded-Proto, and X-Forwarded-Host.
✅ Necessary for reverse proxy setups (e.g., Nginx, Cloudflare, AWS).
✅ Always configure trusted proxies for security.

👉 Have any questions? Drop them in the comments below! 🚀

Monday, January 20, 2025

Dependency Injection AddScoped vs AddTransient in .NET Core

AddScoped vs AddTransient in .NET Core

When building applications with .NET Core, the dependency injection (DI) container is essential for managing object lifetimes. The AddScoped and AddTransient methods define different service lifetimes, and understanding their differences is crucial for optimizing performance and resource usage. In this blog post, we’ll compare these two lifetimes in a clear, tabular format.

Comparison Table: AddScoped vs AddTransient

Feature AddScoped AddTransient
Lifetime Service is created once per request (or scope). Service is created each time it is requested.
Use Case Best suited for stateful or request-specific operations. Ideal for lightweight, stateless operations.
Instance Sharing The same instance is shared across components within the same request. Each component gets its own new instance.
Performance Moderate performance cost since one instance is reused per request. Higher performance cost due to frequent object creation.
Example Scenario Database context or user-specific data during a web request. Utility classes like helper functions or mappers.
Memory Usage Optimized for memory as fewer instances are created per request. Higher memory usage due to multiple instances being created.

Key Points to Consider

Choosing between AddScoped and AddTransient depends on your application’s needs. Here are some guidelines:

  • Use AddScoped when the service should maintain state across a single request or operation.
  • Use AddTransient for lightweight and stateless services where a new instance is required for each use.
  • Evaluate performance and memory trade-offs when deciding which lifetime to use.
Note: Mixing service lifetimes can lead to unexpected behaviors. For example, injecting a scoped service into a singleton service is not recommended and can cause runtime issues.

Conclusion

Understanding the differences between AddScoped and AddTransient is critical for building efficient, scalable, and maintainable .NET Core applications. By selecting the appropriate service lifetime based on your specific requirements, you can ensure optimal resource management and application performance.

Saturday, January 18, 2025

Why .Net Aspire a Game Changer for Enterprise Application Development?

Top 10 Key Features of .NET and Code Examples

.NET is a robust and versatile framework developed by Microsoft, enabling developers to build modern applications. Below are the top 10 features of .NET, explained with code examples to help you understand their application.

1. Cross-Platform Development

.NET Core allows developers to build and run applications on Windows, macOS, and Linux.


using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello, World!");
        Console.WriteLine($"Running on: {Environment.OSVersion}");
    }
}

    

2. Unified Framework

.NET provides a unified platform for web, desktop, mobile, cloud, and IoT development.


using Microsoft.AspNetCore.Mvc;

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

    

3. High Performance

.NET Core offers improved performance with its optimized runtime and compilation.


ReadOnlySpan<char> span = "Hello, World!".AsSpan();
Console.WriteLine(span.Slice(0, 5).ToString()); // Output: Hello

    

4. Asynchronous Programming with async and await

Simplifies writing non-blocking, asynchronous code.


using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        using HttpClient client = new HttpClient();
        string data = await client.GetStringAsync("https://example.com");
        Console.WriteLine(data);
    }
}

    

5. Dependency Injection (DI)

Built-in support for DI simplifies application scalability and testability.


public interface IMyService
{
    string GetData();
}

public class MyService : IMyService
{
    public string GetData() => "Hello from DI!";
}

// In Startup.cs
services.AddSingleton<IMyService, MyService>();

// In Controller
public class HomeController : Controller
{
    private readonly IMyService _myService;

    public HomeController(IMyService myService)
    {
        _myService = myService;
    }

    public IActionResult Index()
    {
        return Content(_myService.GetData());
    }
}

    

6. Entity Framework Core (EF Core)

EF Core simplifies database access with object-relational mapping (ORM).


public class AppDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

// Querying data
using var context = new AppDbContext();
var products = context.Products.ToList();

    

7. Comprehensive Security

Provides secure development with features like authentication, authorization, and data protection.


services.AddDefaultIdentity<IdentityUser>()
        .AddEntityFrameworkStores<AppDbContext>();

    

8. Blazor for WebAssembly

Blazor allows C# to be used for front-end development instead of JavaScript.


@page "/counter"

Counter

Current count: @count

@code { private int count = 0; private void IncrementCount() { count++; } }

9. Open Source

.NET is open source, enabling community-driven development and innovation. Explore and contribute on GitHub.

10. Rich Ecosystem and Tooling

.NET integrates seamlessly with tools like Visual Studio, Azure DevOps, and third-party libraries.


public static class HttpExample
{
    [FunctionName("HttpExample")]
    public static IActionResult Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("Processing HTTP trigger.");
        return new OkObjectResult("Hello, Azure Function!");
    }
}

    

Conclusion

.NET's powerful features, such as cross-platform compatibility, high performance, and modern tooling, make it a go-to choice for developers worldwide. Whether you're building small applications or enterprise-grade systems, .NET offers the versatility and scalability required to meet diverse project needs.

Monday, September 16, 2024

How to inject scope service into Singleton Service ?

 ASP.NET Core has three service lifetimes:

  • Transient
  • Singleton
  • Scoped

    How to resolve inject scope service object into singleton service?  Below SomeSingletonService will inject scope service object and resolve it.