简体   繁体   中英

Why doesn't ASP.NET Core rewrite middleware behave as expected?

            var rewriteOptions = new RewriteOptions();;
            rewriteOptions.AddRewrite("\\/blog\\/[0-9]+", "/blog.html", true);
            app.UseRewriter(rewriteOptions);

I have this middleware added to do url rewriting, to make /blog/ point towards the html page (the JS in this page will extract the integer then make appropriate requests for JSON to get content), yet the redirection isn't taking place (the application behaves as if the rule is absent). What's the issue?

I have this added both before and after the rewrite middleware:

            app.Use(async (context, next) =>
            {
                Console.WriteLine(context.Request.Path + "\n");
                await next.Invoke();
            });

so I know that the path before is what I expect, and that the path is not being rewritten after.

When I added another rule, the first rule started working. Upon further testing, it seems that every rule that I add, except the last, works as expected.

After that, I changed the aforementioned rewrite rule to this:

rewriteOptions.AddRewrite("\\/blog-[0-9]+", "/blog.html", true);

and now it's broken (the application behaves as if the rule is absent), even with another rule after it.

What am I missing?

I found the solution. For some reason that I don't understand, the rewriting middleware removes the preceding "/" from the URL before testiong against regex, so the regex works fine once it's updated to expect this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM