我会尝试创建一个实际的
Regex
变量并重用它。这应该有助于加快速度。我还可能建议将三元业务改为常规的if/elseif/else语句。我认为它更具可读性(只是个人观点)。
string requestedPath = HttpUtility.UrlDecode(this.StripLanguage(currentContext.InputUrl.AbsolutePath));
string requestedPathAndQuery = HttpUtility.UrlDecode(currentContext.InputUrl.PathAndQuery);
string requestedRawUrl = HttpUtility.UrlDecode(currentContext.InputUrl.PathAndQuery);
string requestedUrl =
HttpUtility.UrlDecode(
string.Concat(
currentContext.InputUrl.Scheme,
"://",
currentContext.InputUrl.Host,
requestedRawUrl));
string requestedRawUrlDomainAppended = HttpUtility.UrlDecode(currentContext.InputUrl.AbsoluteUri);
string requestedPathWithCulture = HttpUtility.UrlDecode(currentContext.InputUrl.AbsolutePath);
var regex = new Regex(matchPattern.Trim(), RegexOptions.IgnoreCase);
var finalRequestedURL = regex.IsMatch(requestedPathAndQuery)
? requestedPathAndQuery
: regex.IsMatch(requestedPath)
? requestedPath
: regex.IsMatch(requestedPathWithCulture)
? requestedPathWithCulture
: regex.IsMatch(requestedRawUrl)
? requestedRawUrl
: regex.IsMatch(requestedUrl)
? requestedRawUrlDomainAppended
: string.Empty;
正如我在上面的评论中指出的,有两个相同的字符串,如果删除其中一个字符串,则可以省去比较。
string requestedPath = HttpUtility.UrlDecode(this.StripLanguage(currentContext.InputUrl.AbsolutePath));
string requestedPathAndQuery = HttpUtility.UrlDecode(currentContext.InputUrl.PathAndQuery);
// This string is identical to requestPathAndQuery, so I am removing it
// string requestedRawUrl = HttpUtility.UrlDecode(currentContext.InputUrl.PathAndQuery);
string requestedUrl =
HttpUtility.UrlDecode(
string.Concat(
currentContext.InputUrl.Scheme,
"://",
currentContext.InputUrl.Host,
requestedRawUrl));
string requestedRawUrlDomainAppended = HttpUtility.UrlDecode(currentContext.InputUrl.AbsoluteUri);
string requestedPathWithCulture = HttpUtility.UrlDecode(currentContext.InputUrl.AbsolutePath);
var regex = new Regex(matchPattern.Trim(), RegexOptions.IgnoreCase);
var finalRequestedURL = string.Empty;
// You could even add in brackets here to aid readability but this
// helps remove the indententation/nesting that makes the code harder
// to read and follow
if (regex.IsMatch(requestedPathAndQuery)) finalRequestURL = requestedPathAndQuery;
else if(regex.IsMatch(requestedPath)) finalRequestURL = requestedPath;
else if (regex.IsMatch(requestedPathWithCulture)) finalRequestURL = requestedPathWithCulture;
else if (regex.IsMatch(requestedUrl)) finalRequestURL = requestedRawUrlDomainAppended;