受欢迎的博客标签

How to use URL redirect and URL rewrite Middleware in Asp .Net Core

Published

 

Table of Content

 

Table of Contents

.Net 6.x

Re-Writing a URL

Here's how to handle a Rewrite operation in app.Use() middleware:

app.Use(async (context,next) =>
{
    var url = context.Request.Path.Value;

    // Rewrite to index
    if (url.Contains("/home/privacy"))
    {
        // rewrite and continue processing
        context.Request.Path = "/home/index";
    }

    await next();
});

When in Production I need to redirect all Non WWW to WWW.

step 1:create a custom rule by creating a class and implementing the IRule interface

public class CanonicalDomainRewriteRule : IRule
{
    public void ApplyRule(RewriteContext context)
    {
        HttpRequest request = context.HttpContext.Request;

        if (request.Host.Value.StartsWith("www.", StringComparison.OrdinalIgnoreCase))
        {
            return;
        }
        else
        {
            HttpResponse response = context.HttpContext.Response;

            string redirectUrl = $"{request.Scheme}://www.{request.Host}{request.Path}{request.QueryString}";
            response.Headers[HeaderNames.Location] = redirectUrl;
            response.StatusCode = StatusCodes.Status301MovedPermanently;
            context.Result = RuleResult.EndResponse;
        }
    }
}

step 2:Program.cs

RewriteOptions rewriteOptions = new RewriteOptions()
    .Add(new CanonicalDomainRewriteRule());

app.UseRewriter(rewriteOptions);

 

2.URL Rewriting Middleware in .NET 6.x

Program.cs

using Microsoft.AspNetCore.Rewrite; //RewriteOptions()
var options = new RewriteOptions()
                   .AddRewrite(@"^search.stock.com/search", "search.iasp.com/stock/search/index", skipRemainingRules: false);
app.UseRewriter(options);

 

URL Rewriting Middleware in ASP.NET Core

https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/fundamentals/url-rewriting/samples/6.x/SampleApp/Program.cs

.Net 3.x

using Microsoft.AspNetCore.Rewrite; //RewriteOptions()

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

          var rewriteOptions = new RewriteOptions()
                .AddRedirect(@"\/(ShowNew.asp)", "/Article/List", 301)  //iaspnetcore.com/Article/ShowNew.asp?page=1103
                .AddRedirect(@"\/(\d+).html", "/Article/List")// Redirect using a regular expression ,iaspnetcore.com/Article/ldjh1/qztt/200505/88.html to /Article/List" 302  ,301
                .AddRewrite(@"\/(\d+).asp", "/OldArticle/ShowArticle/$1", skipRemainingRules: true);// Rewrite based on a Regular expression ,www.iaspnetcore.com/Article/allxdth/dxfxcl/200508/2923.asp  

            app.UseRewriter(rewriteOptions);


            app.UseStaticFiles();

            app.UseRouting();
....
}

 

URL redirect and URL rewrite

https://github.com/ldqk/Masuit.MyBlogs/blob/master/src/Masuit.MyBlogs.Core/Extensions/NonWwwRule.cs