Skip to content

Instantly share code, notes, and snippets.

@mpfund
Created February 17, 2021 09:31
Show Gist options
  • Save mpfund/155efe815704fb00f79c6b90c0c39a38 to your computer and use it in GitHub Desktop.
Save mpfund/155efe815704fb00f79c6b90c0c39a38 to your computer and use it in GitHub Desktop.
RegexRewriteWithCapture: a Microsoft.AspNetCore.Rewrite rule with regular expression and variable capture.
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
// use it in controller
var valueFromRegexRewrite = Request.HttpContext.Items["RegexRewriteWithCapture"];
return View(valueFromRegexRewrite);
}
}
using Microsoft.AspNetCore.Rewrite;
using System.Text.RegularExpressions;
// the normal AddRedirect only rewrite the rule and loses the matches
// new RewriteOptions().AddRedirect("/test/(.*)","/handletest")
// if they're not in the redirect itself like
// new RewriteOptions().AddRedirect("/test/(.*)","/handletest/$1")
// RegexRewriteWithCapture captures the first match and redirects.
// it does not support matches in target url like $1, $2 ...
namespace RewriteRuleServerVariable.Configuration
{
public class RegexRewriteWithCapture : IRule
{
private readonly Regex _rule;
private readonly string _redirect;
public RegexRewriteWithCapture(string regexRule, string redirect)
{
_rule = new Regex(regexRule, RegexOptions.Compiled);
_redirect = redirect;
}
public void ApplyRule(RewriteContext context)
{
var request = context.HttpContext.Request;
var match = _rule.Matches(request.Path.Value);
if (match.Count > 0)
{
var response = context.HttpContext.Response;
context.Result = RuleResult.SkipRemainingRules;
context.HttpContext.Items.Add(nameof(RegexRewriteWithCapture), match[0].Value);
context.HttpContext.Request.Path = _redirect;
}
}
}
}
// add it to your Configure startup.cs
//.....
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
// USAGE:
var options = new RewriteOptions()
.Add(new RegexRewriteWithCapture("redirect/rule/(.*)", "/Home/Index"));
app.UseRewriter(options);
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
//.....
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment