解決中文地址Uri.IsWellFormedUriString返回false

时间:2022-02-25 01:23:29

數字和大小寫字母都ok,但是中文地址就會有問題

public bool IslocalURL(string url)
{
if (string.IsNullOrEmpty(url))
{
return false;
}
Uri absoluteUri;
if (Uri.TryCreate(url, UriKind.Absolute, out absoluteUri))
{
return String.Equals(this._httpContext.Request.Url.Host, absoluteUri.Host, StringComparison.OrdinalIgnoreCase);
}
else
{
bool isLocal = !url.StartsWith("http:", StringComparison.OrdinalIgnoreCase)
&& !url.StartsWith("https:", StringComparison.OrdinalIgnoreCase)
&& Uri.IsWellFormedUriString(url, UriKind.Relative);
return isLocal;
}
}

  解決辦法:

利用 Uri.EscapeUriString(String) Method

Converts a URI string to its escaped representation.

public static string EscapeUriString (string stringToEscape);

.

  //解决中文url 不会触发301
pageUrl = Uri.EscapeUriString(pageUrl); //301 (permanent) redirection
if (webHelper.IslocalURL(pageUrl))
{
filterContext.Result = new RedirectResult(pageUrl, true);
}

  參考:

https://docs.microsoft.com/zh-cn/dotnet/api/system.uri?redirectedfrom=MSDN&view=netframework-4.7.2