Last active
June 21, 2016 22:28
-
-
Save DamianEdwards/f5303d30317e945da07dcf6bff3516e4 to your computer and use it in GitHub Desktop.
Ideas for patterns for URL Rewrite middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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