在 .NET Core 中如何简单高效地完成下面的字符串转换?
var originRedirectUri = "https://q.cnblogs.com/account/signin?ReturnUrl=%2F";
转换为
var redirectUri = "https://passport.cnblogs.com/account/signin?ReturnUrl=https%3A%2F%2Fq.cnblogs.com%2F`";
UriBuilder u = new UriBuilder("url");
var q = System.Web.HttpUtility.ParseQueryString(u.Query);
q["ReturnUrl"] = "url";
u.Query = q.ToString();
var url = u.ToString();
在 ASP.NET Core 中使用 Uri + UriBuilder + QueryHelpers 实现了,实现代码如下:
private string BuildAbsoluteRedirectUri(string redirectUri, HttpRequest request)
{
var originUri = new Uri(redirectUri);
var uriBuilder = new UriBuilder("https", "passport.cnblogs.com");
uriBuilder.Path = originUri.AbsolutePath;
var queryStrings = QueryHelpers.ParseQuery(originUri.Query);
var returnUrl = originUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped) + queryStrings["ReturnUrl"];
uriBuilder.Query = QueryString.Create("ReturnUrl", returnUrl).ToString();
return uriBuilder.ToString();
}