Skip to content

Instantly share code, notes, and snippets.

@DamianEdwards
Last active June 21, 2016 22:28
Show Gist options
  • Save DamianEdwards/f5303d30317e945da07dcf6bff3516e4 to your computer and use it in GitHub Desktop.
Save DamianEdwards/f5303d30317e945da07dcf6bff3516e4 to your computer and use it in GitHub Desktop.
Ideas for patterns for URL Rewrite middleware
public class Startup
{
public void Configure()
{
// Raw HTTP->HTTPS redirect using MapWhen
app.MapWhen(
context => context.Request.Scheme == "http",
map => map.Run(context =>
{
// NOTE: Should also handle non-default HTTPS port if required
var req = context.Request;
var newUrl = "https://" + req.Host + req.PathBase + req.Path + req.QueryString;
context.Response.Redirect(newUrl);
return Task.FromResult(0);
})
);
// APPROACH #1: Using a builder
var rewriteBuilder = new UrlRewriteBuilder();
// Adding rules with actions as extension methods
rewriteBuilder.Rewrite(matchUrl: "(?<scheme>.*)//:(.*)", conditions: "{HTTP_HOST} match ^([^_]+)_[^_]+", rewriteTo: "{C:1}/{R:1}");
rewriteBuilder.Redirect(matchUrl: "(.*)", conditions: "{HTTP_SCHEME} == http", redirectTo: "");
// Adding rules with matches/conditions as extension methods
rewriteBuilder.MatchUrl("^http://(?<url>\.+)",
rwc => {
// Need to handle non-default HTTPS port if required
var newUrl = "https://" + rwc["url"];
map.Run(c => c.Response.Redirect(newUrl));
});
// Add the builder output to the HTTP pipeline
app.UseUrlRewriter(rewriteBuilder.Build());
// APPROACH #2: Using just a list of "rules"
var redirectToHttps = new UrlRewriteRule();
// URL matching as a first-class concept
redirectToHttps.UrlMatch = "^http://(?<url>\.+)";
// URL matching as just another condition, added via extension method
redirectToHttps.Conditions.AddUrlMatch("^http://(?<url>\.+)");
// Adding a further condition with an extension method
redirectToHttps.Conditions.AddCookieMatch("MY_COOKIE", "true");
// Adding a further condition as a predicate
redirectToHttps.Conditions.Add(rwc => rwc.Request.Cookies["MY_COOKIE"] == "true");
// Setting the action to perform when the rule is matched
redirectToHttps.Action = rwc => {
// Need to handle non-default HTTPS port if required
var newUrl = "https://" + rwc["url"];
map.Run(c => rwc.Response.Redirect(newUrl));
};
// Add the rules to the HTTP pipeline
app.UseUrlRewriter(new [] { redirectToHttps });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment