asp.net-core.net-corekestrel-http-serverurl-rewrite-module

UrlRewrite module for .NET Core using Kestrel


We are migrating an application from .NET framework 4.6 to .NET Core 6 running on Kestrel. In the old application (running on IIS7), we could install urlRewrite module in IIS and write all sorts of rewrite and redirect rules using server variables (e.g. HTTP_HOST, PATH, REQUEST_URI, QUERY_STRING). The module offered so many out of the box options so that it was easy to configure a specific rule we wanted to implement.

I am just puzzled on how to implement such complex rules in .NET Core. All the articles are pointing to writing custom rules in code, but it would mean re-investing the wheel!

Is there no nuget package that I can use to write such rules in appsettings.json file? Any pointers to a solution that will save me hours of coding time (besides testing and bug fixing time)?


Solution

  • You could use rewrite in ASP.NET core like this in program.cs:
    (rewrite "/test/xxx" to "/xxx")

    using (StreamReader iisUrlRewriteStreamReader =
        File.OpenText("IISUrlRewrite.xml"))
    {
        var options = new RewriteOptions();
        options.AddIISUrlRewrite(iisUrlRewriteStreamReader);
        app.UseRewriter(options);
    }
    

    IISUrlRewrite.xml

    <rewrite>
        <rules>
            <rule name="Rewrite1" stopProcessing="true">
                <match url="test/(.*)" />
                <action type="Rewrite" url="{R:1}" appendQueryString="false"/>
            </rule>
        </rules>
    </rewrite>
    

    Result
    enter image description here

    Reference: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/url-rewriting?view=aspnetcore-8.0