asp.net-corehttp-redirect.net-coreasp.net-core-5.0no-www

In .Net Core 5, How to redirect www to non-www URL?


On a subdomain want to redirect all requests with www to non-www, because of that, using this line of code in the "Start.up", in the "Configure" method like below but it doesn't work.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseRewriter(new RewriteOptions().AddRedirectToNonWww());
            ...
        }
   ...
}

What's wrong with my codes? I don't want to write some extra codes like this, because it seems there is a function to handle it.


Solution

  • in .net Core 5 put the follow code inside Strartup.cs Configure function

     app.UseRewriter(new RewriteOptions()
                .AddRedirectToNonWwwPermanent()
                .AddRedirectToHttps()
             );
    

    If you use .net Core 6 put the code inside program.cs