问题描述
我无法正确编写URL重写中间件.我认为正则表达式是正确的.我第一次使用此功能,也许我听不懂.
I can't write correctly a URL Rewriting Middleware. I think the regex is correct. I use this functionality for the first time and maybe I do not understand something.
示例网址:
http://localhost:55830/shop/alefajniealsdnoqwwdnanxc!@#lxncqihen41j2ln4nkzcbjnzxncas?valueId=116
http://localhost:55830/shop/whatever?valueId=116
http://localhost:55830/shop/toquestionmark?valueId=116
正则表达式:
\/shop\/([^\/?]*)(?=[^\/]*$)
启动,配置:
var rewrite = new RewriteOptions().AddRewrite(
@"\/shop\/([^\/?]*)(?=[^\/]*$)",
"/shop/$1",
true
);
app.UseRewriter(rewrite);
也许与其他方法相关的顺序有问题吗?
Maybe the order related to another methods have matters?
控制器:
[Route(RouteUrl.Listing + RouteUrl.Slash + "{" + ActionFilter.Value + "?}", Name = RouteUrl.Name.ShopBase)]
public ActionResult Index(string value, int valueId)
{
return View();
}
例如,当我重定向到:
我想显示如下网址:
推荐答案
基于本文: https://www.softfluent .com/blog/dev/Page-redirection-and-URL-Rewriting-with-ASP-NET-Core
我想解释一下重定向和重写之间的区别.重定向发送HTTP 301或302到客户端,告诉客户端它应该使用另一个URL访问该页面.浏览器将更新在地址栏中可见的URL,并使用新URL发出新请求.另一方面,重写发生在服务器上,是一个URL到另一个URL的转换.服务器将使用新的URL来处理请求.客户端不知道服务器已经重写了URL.
I want to explain the difference between redirection and rewrite. Redirecting sends a HTTP 301 or 302 to the client, telling the client that it should access the page using another URL. The browser will update the URL visible in the address bar, and make a new request using the new URL. On the other hand, rewriting happens on the server, and is a translation of one URL to another. The server will use the new URL to process the request. The client doesn't know that the server has rewritten the URL.
对于IIS,您可以使用web.config
文件来定义重定向和重写规则,或者使用RewritePath
:
With IIS, you can use the web.config
file to define the redirection and rewrite rules or use RewritePath
:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Redirect to https">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="Off" />
<add input="{REQUEST_METHOD}" pattern="^get$|^head$" />
<add input="{HTTP_HOST}" negate="true" pattern="localhost" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
但是,这不适用于ASP.NET Core.相反,您可以使用新的NuGet包:Microsoft.AspNetCore.Rewrite(GitHub).该软件包非常易于使用.打开startup.cs文件并编辑Configure方法:
However, this doesn't work anymore with ASP.NET Core. Instead, you can use the new NuGet package: Microsoft.AspNetCore.Rewrite (GitHub). This package is very easy to use. Open the startup.cs file and edit the Configure method:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ISiteProvider siteProvider)
{
app.UseRewriter(new RewriteOptions()
.AddRedirectToHttps()
.AddRedirect(@"^section1/(.*)", "new/$1", (int)HttpStatusCode.Redirect)
.AddRedirect(@"^section2/(\\d+)/(.*)", "new/$1/$2", (int)HttpStatusCode.MovedPermanently)
.AddRewrite("^feed$", "/?format=rss", skipRemainingRules: false));
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
Microsoft已决定帮助您使用此新程序包.确实,如果您已经有一个web.config文件或什至一个.htaccess文件(.net核心是跨平台的),则可以直接将它们导入:
Microsoft has decided to help you using this new package. Indeed, if you already have a web.config file or even an .htaccess file (.net core is cross platform) you can import them directly:
app.UseRewriter(new RewriteOptions()
.AddIISUrlRewrite(env.ContentRootFileProvider, "web.config")
.AddApacheModRewrite(env.ContentRootFileProvider, ".htaccess"));
如果您有无法使用正则表达式表达的复杂规则,则可以编写自己的规则.规则是实现Microsoft.AspNetCore.Rewrite.IRule的类:
If you have complex rules that can't be expressed using a regex, you can write your own rule. A rule is a class that implements Microsoft.AspNetCore.Rewrite.IRule:
// app.UseRewriter(new RewriteOptions().Add(new RedirectWwwRule()));
public class RedirectWwwRule : Microsoft.AspNetCore.Rewrite.IRule
{
public int StatusCode { get; } = (int)HttpStatusCode.MovedPermanently;
public bool ExcludeLocalhost { get; set; } = true;
public void ApplyRule(RewriteContext context)
{
var request = context.HttpContext.Request;
var host = request.Host;
if (host.Host.StartsWith("www", StringComparison.OrdinalIgnoreCase))
{
context.Result = RuleResult.ContinueRules;
return;
}
if (ExcludeLocalhost && string.Equals(host.Host, "localhost", StringComparison.OrdinalIgnoreCase))
{
context.Result = RuleResult.ContinueRules;
return;
}
string newPath = request.Scheme + "://www." + host.Value + request.PathBase + request.Path + request.QueryString;
var response = context.HttpContext.Response;
response.StatusCode = StatusCode;
response.Headers[HeaderNames.Location] = newPath;
context.Result = RuleResult.EndResponse; // Do not continue processing the request
}
}
这篇关于URL重写中间件ASP.Net Core 2.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!