Search code examples
c#.netasp.net-mvcasp.net-core

Is it possible to redirect request from middleware in .net core


What I'm trying to achieve is this: When someone visits: smartphone.webshop.nl/home/index I want to redirect this from middle ware to: webshop.nl/smartphone/home/index

I want to do this because I want to create a generic controller which get data from database based on sub-domein. So I need all the calls come to the same controller.

This is my middleware now:

public Task Invoke(HttpContext context)
    {
        var subDomain = string.Empty;

        var host = context.Request.Host.Host;

        if (!string.IsNullOrWhiteSpace(host))
        {
            subDomain = host.Split('.')[0]; // Redirect to this subdomain
        }

        return this._next(context);
    }

How can I redirect and how should my controller/mvc config look like?

I'm pretty new to .net core so please be clear in your answers. Thank you.


Solution

  • That's called URL Rewriting and ASP.NET Core already have special middleware for that (in package Microsoft.AspNetCore.Rewrite).

    On your configuration file, you can have something like this:

    using Microsoft.AspNetCore.Rewrite;
    using RewriteRules;
    
    var builder = WebApplication.CreateBuilder(args);
    var app = builder.Build();
    var options = new RewriteOptions()
                 .AddRewrite(@"^smartphone.webshop.nl/(.*)", "webshop.nl/smartphone/$1", skipRemainingRules: true);
    
    app.UseRewriter(options);
    

    If you want to do something more elaborated, you can either implement a method-base rule or check source code and write your own middleware.