ASP.NET Core URL重写 [英] ASP.NET Core URL Rewriting
问题描述
我正在尝试将我的网站从www重定向到非www规则,以及将http重定向到https( https://example.com ).我曾经在web.config中进行这些重定向更改,例如:
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>
我是asp.net核心的新手,想知道如何在中间件中进行这些重定向?我阅读了这篇文章: https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/url-rewriting ,但这并不能帮助我强制将www重定向到非www.
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.
推荐答案
安装以下NuGet软件包:
Install the following NuGet package:
Microsoft.AspNetCore.Rewrite
添加以下行:
app.UseCustomRewriter();
内部:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
在调用.UseMvc
方法之前.
并将以下扩展类添加到您的项目中:
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);
}
}
在RewriteOptions中,您可以提供重写配置.
Within RewriteOptions you can provide your rewrite configuration.
箍,这将帮助您.
最诚挚的问候, 科林
这篇关于ASP.NET Core URL重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!