Skip to content

Commit

Permalink
IgnoreQueryString & PreserveQueryString
Browse files Browse the repository at this point in the history
  • Loading branch information
patrickdemooij9 committed Dec 4, 2022
1 parent 43cba67 commit 876fea8
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
Expand Down Expand Up @@ -76,15 +77,18 @@ public async Task Invoke(HttpContext context)

private bool HandleRedirect(HttpContext context)
{
var url = new Uri(context.Request.GetEncodedUrl());
var fullUrl = context.Request.GetEncodedUrl();
if (_config.IgnoreQueryString)
fullUrl = fullUrl.Split('?').First();
var url = new Uri(fullUrl);
var matchedRedirect = _redirectRepository.FindRedirect(url);
if (matchedRedirect == null)
{
return false;
};

var isPerm = matchedRedirect.RedirectCode == (int)HttpStatusCode.MovedPermanently;
context.Response.Redirect(matchedRedirect.GetNewUrl(url), isPerm);
context.Response.Redirect(matchedRedirect.GetNewUrl(new Uri(context.Request.GetEncodedUrl()), _config.PreserveQueryString), isPerm);
return true;
}
}
Expand Down
22 changes: 20 additions & 2 deletions source/SimpleRedirects.Core/Models/Redirect.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using NPoco;
Expand Down Expand Up @@ -41,10 +43,26 @@ public class Redirect
[JsonProperty("notes")]
public string Notes { get; set; }

public string GetNewUrl(Uri uri)
public string GetNewUrl(Uri uri, bool preserveQueryString)
{
if (!IsRegex || !NewUrl.Contains($"$"))
return NewUrl;
{
var url = NewUrl;
if (!preserveQueryString ||
!Uri.TryCreate(NewUrl, UriKind.RelativeOrAbsolute, out var _)) return url;

var index = url.IndexOf('?');
var queryString = index >= 0 ? url.Substring(index) : "";
var query = HttpUtility.ParseQueryString(queryString);
var appendQuery = HttpUtility.ParseQueryString(uri.Query);
foreach (var item in appendQuery.AllKeys)
{
query[item] = appendQuery.Get(item);
}

url = $"{url.Split('?').First()}{(query.Count > 0 ? $"?{query}" : string.Empty)}";
return url;
}

try
{
Expand Down
2 changes: 2 additions & 0 deletions source/SimpleRedirects.Core/Options/SimpleRedirectsOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,7 @@ public class SimpleRedirectsOptions
public bool CacheEnabled {get; set;} = true;
public int CacheDuration {get; set;} = 86400;
public bool OnlyRedirectOn404 { get; set; } = false;
public bool IgnoreQueryString { get; set; } = false;
public bool PreserveQueryString { get; set; } = false;
}
}

0 comments on commit 876fea8

Please sign in to comment.