问题
如何在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/
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
- 浅谈ASP.NET Core 2.0 带初始参数的中间件(译)
- 浅谈ASP.NET Core 2.0 中间件(译)
- ASP.NET Core 2.0 带初始参数的中间件问题及解决方法
- ASP.NET Core 2.0 使用支付宝PC网站支付实现代码
- ASP.NET Core 2.0 支付宝扫码支付的实现代码
- CodeFirst从零开始搭建Asp.Net Core2.0网站
- Amazing ASP.NET Core 2.0