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 :: ASP.NET Core: Customizing HTTP Headers with Middleware

clock October 14, 2024 08:04 by author Peter

We'll attempt to use custom middleware to alter HttpResponse in this post. After developing custom middleware, we will alter the response. The middleware will alter the HttpResponse each time the request is returned to the client.

public class CustomResponseMiddleWare
{
    private readonly RequestDelegate _next;
    public CustomResponseMiddleWare(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        context.Response.Headers["CustomHeader"] = "This middleware added by Peter";
        await _next(context);
    }
}

We have created custom middleware and added a new header at the invoke method.

Program.cs
using SampleHttpResponseModify;

var builder = WebApplication.CreateBuilder(args);
// Add services to the container
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Use custom middleware
app.UseMiddleware<CustomResponseMiddleWare>();
// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();


Register middleware at the program. cs.
app.UseMiddleware<CustomResponseMiddleWare>();

When we ran the application and inspected it, we found a custom-added header in the response.Now let us try to modify the Http header when a particular API is called.
Consider i want to add an extra header when we call weather API only then do we have to add condition on middleware like below.
public class CustomResponseMiddleWare
{
    private readonly RequestDelegate _next;
    public CustomResponseMiddleWare(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        context.Response.Headers["CustomHeader"] = "This middleware added by Peter";
        if (context.Request.Path.Value == "/WeatherForecast")
        {
            context.Response.Headers["CustomeHeadernparticularRequest"] = "This is header added when this path found";
        }
        await _next(context);
    }
}

We have added the below condition only, so if the below path is found then only add an extra header.
if (context.Request.Path.Value == "/WeatherForecast")
{
    context.Response.Headers["CustomeHeadernparticularRequest"] = "This is header added when this path found";
}

Response on WeatherForcast API. We can see the additional header is coming.

Another learning point here is a sequence of middleware in the program.cs. If we move the position of UseMiddleware then we will find that this middleware is not calling due to incorrect positions or order of middleware.

Conclusion
We have learned about how to modify http headers using custom middleware. Keep learning and Keep Enjoying.

HostForLIFE ASP.NET Core 9.0 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 9.0 Hosting - HostForLIFE :: ​Simple Load Balancer in .NET Core with YARP

clock October 8, 2024 08:55 by author Peter

Load balancing is essential in distributed systems and web applications to ensure that traffic is efficiently distributed across multiple servers or resources.

Reverse Proxy

A reverse proxy is a server that sits between client devices (e.g., browsers) and the backend servers, forwarding client requests to the appropriate server and then returning the server's response to the client.

Sticky Sessions

Sticky sessions (also known as Session Affinity) in YARP is a feature that ensures requests from a particular client are always routed to the same backend server. This is particularly important for applications that rely on server-side session data, such as when storing user state or authentication information in memory on specific servers.

YARP(Yet Another Reverse Proxy) Setup

create a new ASP.NET Core web appliLoad balancing is essential in distributed systems and web applications to ensure that traffic is efficiently distributed across multiple servers or resources.

Reverse Proxy

A reverse proxy is a server that sits between client devices (e.g., browsers) and the backend servers, forwarding client requests to the appropriate server and then returning the server's response to the client.

Sticky Sessions

Sticky sessions (also known as Session Affinity) in YARP is a feature that ensures requests from a particular client are always routed to the same backend server. This is particularly important for applications that rely on server-side session data, such as when storing user state or authentication information in memory on specific servers.

YARP(Yet Another Reverse Proxy) Setup

  • create a new ASP.NET Core web application
  • Install the Yarp.ReverseProxy NuGet package

Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddReverseProxy().LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));

var app = builder.Build();
app.MapReverseProxy();

app.Run();


appsettings.json
{
  "ReverseProxy": {
    "Routes": {
      "api-route": {
        "ClusterId": "api-cluster",
        "Match": {
          "Path": "{**catch-all}"
        },
        "Transforms": [
          { "PathPattern": "{**catch-all}" }
        ]
      }
    },
    "Clusters": {
      "api-cluster": {
        "SessionAffinity": {
          "Enabled": "true",
          "AffinityKeyName": "Key1",
          "Cookie": {
            "Domain": "localhost",
            "Expiration": "03:00:00",
            "IsEssential": true,
            "MaxAge": "1.00:00:00",
            "SameSite": "Strict",
            "SecurePolicy": "Always"
          }
        },
          "LoadBalancingPolicy": "RoundRobin",
          "Destinations": {
            "destination1": {
              "Address": "https://localhost:7106"
            },
            "destination2": {
              "Address": "https://localhost:7107"
            }
          }
        }
      }
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Destination Address: The destination address should point to the base URL of your hosted web application.

Output
Here is the console output of round-robin policy.

Load balancer

Summary
Load balancing helps in improving the scalability, performance, availability, and security of web applications and services.

HostForLIFE ASP.NET Core 9.0 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 9.0 Hosting - HostForLIFE :: ​Implementing CORS in .NET Core 8

clock October 4, 2024 07:56 by author Peter

Web pages are prohibited from sending requests to a domain other than the one that provided them thanks to a security feature called Cross-Origin Resource Sharing, or CORS. Building safe and useful apps in modern web development requires knowing how to properly implement CORS, especially when utilizing Angular as a front-end framework and.NET Core 8 as a backend. The best practices and typical pitfalls for configuring CORS in a.NET Core 8 environment are described in this article.

Assume you have a friend who lives next door (another website) and a toy box at home (your website). Your mom (the browser) has a rule that states your friend can only play with their own toys. Your friend wants to play with your toys (data) in your toy box. This is to ensure that everything is secure and safe. Assume that your friend's website is funfriend.com and that yours is mycooltoys.com. CORS checks are performed if funfriend.com requests to borrow a toy from mycooltoys.com.

  • Is funfriend.com allowed to borrow toys from mycooltoys.com?
  • Did they follow the rules about how to ask?
  • If everything is good, then your friend can borrow the toy!

Setting Up CORS in .NET Core 8

  • Install Necessary Packages: If you haven't already, ensure you have the required .NET Core packages installed. In most cases, the default setup will suffice, but you can install any specific CORS libraries if needed.
  • Configure CORS in Startup: In .NET Core 8, the configuration of CORS is typically done in the Program.cs file. Here’s a simple setup.

    var builder = WebApplication.CreateBuilder(args);
    // Add CORS services
    builder.Services.AddCors(options =>
    {
        options.AddPolicy("AllowAngularApp",
            builder => builder.WithOrigins("https://your-angular-app.com")
                              .AllowAnyMethod()
                              .AllowAnyHeader()
                              .AllowCredentials());
    });
    var app = builder.Build();
    // Use CORS policy
    app.UseCors("AllowAngularApp");
    app.MapControllers();
    app.Run();


  • Allowing Specific Origins: For production environments, it’s crucial to specify the exact origin rather than using AllowAnyOrigin(), which is a common pitfall. Limiting allowed origins enhances security.

options.AddPolicy("AllowAngularApp",
    builder => builder.WithOrigins("https://your-angular-app.com")
                      .AllowAnyMethod()
                      .AllowAnyHeader());

  • Handling Preflight Requests: Ensure your server can handle preflight requests. These are OPTIONS requests sent by browsers to check permissions. By enabling CORS and handling these requests, you ensure that your application can respond correctly.
  • Allow Credentials: If your Angular application needs to send cookies or HTTP authentication information, you need to set AllowCredentials() in your CORS policy. Be cautious with this feature, as it requires that the origin is explicitly specified and cannot be set to AllowAnyOrigin().

Advanced CORS Configuration

  • Customizing Allowed Methods: You can customize allowed methods if your API uses specific HTTP methods.

    options.AddPolicy("AllowAngularApp",
        builder => builder.WithOrigins("https://your-angular-app.com")
                          .WithMethods("GET", "POST", "PUT", "DELETE")
                          .AllowAnyHeader()
                          .AllowCredentials());


Setting Exposed Headers: If your API returns custom headers that the client needs to access, specify these using WithExposedHeaders.

options.AddPolicy("AllowAngularApp",
    builder => builder.WithOrigins("https://your-angular-app.com")
                      .AllowAnyMethod()
                      .AllowAnyHeader()
                      .WithExposedHeaders("X-Custom-Header")
                      .AllowCredentials());

Logging CORS Requests: For debugging purposes, you can log CORS requests to track any issues that arise. Here’s a simple logging middleware.
app.Use(async (context, next) =>
{
    if (context.Request.Headers.ContainsKey("Origin"))
    {
        var origin = context.Request.Headers["Origin"];
        Console.WriteLine($"CORS request from: {origin}");
    }
    await next();
});

Best Practices

  • Limit Origins: Always specify the exact origins that are permitted to interact with your API. Avoid using wildcards (*) as they expose your API to potential security risks.
  • Use HTTPS: Ensure both your .NET Core backend and Angular frontend are served over HTTPS. This secures data in transit and enhances trustworthiness.
  • Regularly Review CORS Policies: As your application grows and evolves, periodically review your CORS configurations to ensure they align with current security requirements.
  • Test CORS Configurations: Use tools like Postman or browser developer tools to test your CORS setup. Check for errors and ensure your API is returning the expected headers.
  • Document Your API: Clearly document the CORS policies and allowed origins in your API documentation. This helps other developers understand how to interact with your API correctly.

Common Pitfalls

  • Misconfigured Allowed Origins: One of the most frequent mistakes is misconfiguring allowed origins. Double-check the exact URLs, including the protocol (HTTP vs. HTTPS) and any potential trailing slashes.
  • Forgetting to Apply CORS Middleware: Ensure that the UseCors middleware is applied before any endpoints are mapped. Placing it after endpoint mapping can lead to unexpected behaviors.
  • AllowAnyOrigin with AllowCredentials: This combination is not allowed and will cause CORS requests to fail. If you need credentials, specify the exact origins.
  • Not Handling OPTIONS Requests: Ignoring the preflight OPTIONS requests can lead to issues when your API is accessed from different origins. Ensure your server can properly handle these requests.

Example
Default

Allowing Specific Origins

Conclusion
Implementing CORS in .NET Core 8 for Angular applications is crucial for creating a secure and functional web application. By following best practices and being aware of common pitfalls, you can ensure that your CORS setup is both effective and secure. Regularly revisiting your CORS configuration as your application evolves will help maintain security and functionality in the long run.

Happy Coding!

HostForLIFE ASP.NET Core 9.0 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