ASP.NET Core URL Rewriting

爷,独闯天下 提交于 2020-02-28 06:09:11

问题


I am trying to redirect my website from www to non-www rules as well as http to https (https://example.com) in the middleware. I used to make those redirection change in the web.config such as:

 <rewrite>
  <rules>
    <clear />
    <rule name="Redirect to https" stopProcessing="true">
      <match url=".*" />
      <conditions>
        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
    </rule>
    <rule name="Redirects to www.domain.com" patternSyntax="ECMAScript" 
            stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAny">
            <add input="{HTTP_HOST}" pattern="^example.com$" />
        </conditions>
        <action type="Redirect" url="https://www.example.com/{R:0}" />
    </rule>

I am new to asp.net core and would like to know how can i make those redirection in my middleware? I read this article: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/url-rewriting but it didn't help me to force redirect my www to non-www.


回答1:


Install the following NuGet package:

Microsoft.AspNetCore.Rewrite

Add the following line:

app.UseCustomRewriter();

within:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)

Before calling .UseMvc method.

And add the following extensions class to your project:

public static class ApplicationBuilderExtensions
{
    public static IApplicationBuilder UseCustomRewriter(this IApplicationBuilder app)
    {
        var options = new RewriteOptions()
            .AddRedirectToHttpsPermanent()
            .AddPermanentRedirect("(.*)/$", "$1");

        return app.UseRewriter(options);
    }
}

Within RewriteOptions you can provide your rewrite configuration.

Hoops this will help you out.

Best regards, Colin



来源:https://stackoverflow.com/questions/43413226/asp-net-core-url-rewriting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!