問題
如何在ASP.NET Core 2.0中實現網址重定向?
答案
新建一個空項目,在Startup.cs文件中,配置RewriteOptions參數並添加網址重定向中間件(UseRewriter):
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var rewrite = new RewriteOptions()
.AddRedirect("films", "movies")
.AddRewrite("actors", "stars", true);
app.UseRewriter(rewrite);
app.Run(async (context) =>
{
var path = context.Request.Path;
var query = context.Request.QueryString;
await context.Response.WriteAsync($"New URL: {path}{query}");
});
}
運行,並在瀏覽器地址欄輸入:http://localhost:56825/films,通過客戶端調試工具觀察重定向過程:

在地址欄輸入:http://localhost:56825/actors,再次觀察重定向過程:

討論
網址重定向就是根據用戶自定義規則來修改請求的網址,目的是為了將服務器資源和瀏覽器網址解綁定。這樣做可能是出於安全考慮, 搜索引擎優化(SEO),用戶友好網址,將HTTP重定向到HTTPS等多種目的。
當你無法使用Web服務器(IIS,Apache,Nginx)的重定向功能時,ASP.NET Core提供了一個可選項 - 請求網址重定向中間件。然后它的性能和功能比不上Web服務器的重定向。
重定向中間件可以做兩件事情:客戶端重定向和服務器重寫:
重定向(客戶端)
這是一個客戶端操作,工作流程如下:
1. 客戶端請求一個資源,比如 /films
2. 服務器返回301(Moved Permanently)或者302(Found)狀態碼,並在響應頭中添加Location屬性,用來指示瀏覽器請求新的地址(比如/movies)。
3. 客戶端請求新的地址,並顯示在瀏覽器的地址欄中。
重寫(服務端)
它是一個服務器端操作,工作流程如下:
1. 客戶端請求一個資源,比如 /actors
2. 服務器將其內部映射到新的地址(比如/stars)並且返回200(OK)。
在此過程中,客戶端並不知道服務器端的內部映射操作,因此用戶看到的瀏覽器地址欄依然顯示的是最初請求地址。
規則
重定向和重寫規則可以是正則表達式,更加詳細的信息請參考:https://docs.microsoft.com/en-gb/aspnet/core/fundamentals/url-rewriting
自定義重定向規則
我們也可以自定義重定向規則,通過一個繼承自IRule接口的類來實現:
public class MoviesRedirectRule : IRule
{
private readonly string[] _matchPaths;
private readonly string _newPath;
public MoviesRedirectRule(string[] matchPaths, string newPath)
{
_matchPaths = matchPaths;
_newPath = newPath;
}
public void ApplyRule(RewriteContext context)
{
var request = context.HttpContext.Request;
// 已經是目標地址了,直接返回
if (request.Path.StartsWithSegments(new PathString(_newPath)))
{
return;
}
if (_matchPaths.Contains(request.Path.Value))
{
var newLocation = $"{_newPath}{request.QueryString}";
var response = context.HttpContext.Response;
response.StatusCode = StatusCodes.Status302Found;
context.Result = RuleResult.EndResponse;
response.Headers[HeaderNames.Location] = newLocation;
}
}
}
然后在Configure()中,將此自定義規則添加到RewriteOptions里面:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var rewrite = new RewriteOptions()
.Add(new MoviesRedirectRule(
matchPaths: new string[] { "/films", "/features", "/albums" },
newPath: "/movies"));
app.UseRewriter(rewrite);
app.Run(async (context) =>
{
var path = context.Request.Path;
var query = context.Request.QueryString;
await context.Response.WriteAsync($"New URL: {path}{query}");
});
}
運行,在地址欄輸入:http://localhost:56825/films?id=123,觀察重定向過程:

源代碼下載
原文:https://tahirnaushad.com/2017/08/18/url-rewriting-in-asp-net-core/
