"
ASP.NET (snapshot 2017) Microsoft documentation and samplesThis sample illustrates usage of ASP.NET Core 2.x URL Rewriting Middleware. The application demonstrates URL redirect and URL rewriting options. For the ASP.NET Core 1.x sample, see ASP.NET Core URL Rewriting Sample (ASP.NET Core 1.x).
When running the sample, a response will be served that shows the rewritten or redirected URL when one of the rules is applied to a request URL.
AddRedirect("redirect-rule/(.*)", "$1")
AddRewrite(@"^rewrite-rule/(\d+)/(\d+)", "rewritten?var1=$1&var2=$2", skipRemainingRules: true)
AddApacheModRewrite(env.ContentRootFileProvider, "ApacheModRewrite.txt")
AddIISUrlRewrite(env.ContentRootFileProvider, "IISUrlRewrite.xml")
Add(RedirectXMLRequests)
Add(new RedirectPNGRequests(".png", "/png-images")))
Add(new RedirectPNGRequests(".jpg", "/jpg-images")))
PhysicalFileProvider
You can also obtain an IFileProvider
by creating a PhysicalFileProvider
to pass into the AddApacheModRewrite()
and AddIISUrlRewrite()
methods:
using Microsoft.Extensions.FileProviders;
PhysicalFileProvider fileProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory());
This sample includes WebHostBuilder
configuration for the app to use URLs (https://localhost:5001, https://localhost) and a test certificate (testCert.pfx) to assist you in exploring these redirect methods. Add any of them to the RewriteOptions()
in Startup.cs to study their behavior.
Method | Status Code | Port |
---|---|---|
.AddRedirectToHttpsPermanent() |
301 | null (465) |
.AddRedirectToHttps() |
302 | null (465) |
.AddRedirectToHttps(301) |
301 | null (465) |
.AddRedirectToHttps(301, 5001) |
301 | 5001 |