我想获取原始 URL,截断查询字符串参数,并返回 URL 的清理版本。我希望它发生在整个应用程序中,因此通过 global.asax 执行将是理想的。另外,我认为 301 重定向也是合适的。
即。
在:www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media
出处:www.website.com/default.aspx
实现此目标的最佳方法是什么?
最佳答案
System.Uri 是你的 friend 。这上面有许多有用的实用程序,但您需要的是 GetLeftPart:
string url = "http://www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media";
Uri uri = new Uri(url);
Console.WriteLine(uri.GetLeftPart(UriPartial.Path));
这给出了输出:http://www.website.com/default.aspx
[Uri 类确实需要指定协议(protocol) http://]
GetLeftPart 基本上是说“获取 uri 的左侧部分直到并包括我指定的部分”。这可以是 Scheme(只是 http://位)、Authority(www.website.com 部分)、Path(/default.aspx)或 Query(查询字符串)。
假设您在 aspx 网页上,然后您可以使用 Response.Redirect(newUrl) 来重定向调用者。
希望对你有帮助
关于c# - 截断查询字符串并返回干净的 URL C# ASP.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1188096/