ResolveUrl in ASP.NET - The Perfect Solution
Introduction/Background
From my personal experience using ASP.NET, and from searching the web, I have found that the ResolveUrlmethod of the Page control (and basically, Control) presents us with some serious problems.
The most common one is that you just cannot use it outside of the page or control context.
Other problems are just bugs. It will not correctly handle some of the URLs you'll give it. For example, tryPage.ResolveUrl("~/test.aspx?param=http://www.test.com"). The result is the very same input string... It will just do nothing. By looking into the ASP.NET code using Reflector, I found that all mechanisms that are supposed to convert the relative URLs to absolute URLs will search first for a "://" inside the string, and will return if found. So a query string is OK, unless you pass in a parameter with ://. Yes, I know that the query string parameter should be UrlEncoded, but if it isn't, it is still an acceptable URL. Seriously, check your browsers!
Other suggested methods on the web involve using VirtualPathUtility.ToAbsolute, which is pretty nice and handy, unless you pass in a query string with the URL... Because it will just throw an exception. It will also throw an exception for an absolute URL!
So I decided to find the ultimate solution.
Using the Code
First, I searched for the perfect variable that will give me the Application Virtual Path at runtime without a page context.
I found this to be HttpRuntime.AppDomainAppVirtualPath. It will work anywhere - even inside a timer callback! It gives the path without a trailing slash (ASP.NET makes a special effort to remove the trailing slash...), but that is OK, we can fix it 
Then, I did some tests on the original ResolveUrl code, and found where I need to replace what with theAppVirtualPath:
- When the URL begins with a slash (either / or \), it will not touch it!
- When the URL begins with ~/, it will replace it with the
AppVirtualPath. - When the URL is an absolute URL, it will not touch it. (
ResolveUrlhas a bug with this, as I said before...) - In any other case (even beginning with ~, but not slash), it will append the URL to the
AppVirtualPath. - Whenever it modifies the URL, it also fixes up the slashes. Removes double slashes and replaces \ with /.
So I replicated all of that, but without the bugs. And here's the code:
Collapse | Copy Codepublic static string ResolveUrl(string relativeUrl)
{
if (relativeUrl == null) throw new ArgumentNullException("relativeUrl"); if (relativeUrl.Length == 0 || relativeUrl[0] == '/' || relativeUrl[0] == '\\')
return relativeUrl; int idxOfScheme = relativeUrl.IndexOf(@"://", StringComparison.Ordinal);
if (idxOfScheme != -1)
{
int idxOfQM = relativeUrl.IndexOf('?');
if (idxOfQM == -1 || idxOfQM > idxOfScheme) return relativeUrl;
} StringBuilder sbUrl = new StringBuilder();
sbUrl.Append(HttpRuntime.AppDomainAppVirtualPath);
if (sbUrl.Length == 0 || sbUrl[sbUrl.Length - 1] != '/') sbUrl.Append('/'); // found question mark already? query string, do not touch!
bool foundQM = false;
bool foundSlash; // the latest char was a slash?
if (relativeUrl.Length > 1
&& relativeUrl[0] == '~'
&& (relativeUrl[1] == '/' || relativeUrl[1] == '\\'))
{
relativeUrl = relativeUrl.Substring(2);
foundSlash = true;
}
else foundSlash = false;
foreach (char c in relativeUrl)
{
if (!foundQM)
{
if (c == '?') foundQM = true;
else
{
if (c == '/' || c == '\\')
{
if (foundSlash) continue;
else
{
sbUrl.Append('/');
foundSlash = true;
continue;
}
}
else if (foundSlash) foundSlash = false;
}
}
sbUrl.Append(c);
} return sbUrl.ToString();
}
Points of Interest
After completing the code and testing over and over again and comparing to the original ResolveUrl, I started to test for performance... In most cases, my code executed faster than the original ResolveUrl by 2.7 times! I also tested inside loops that executed the code 100000s of times on different kinds of URLs.
ResolveUrl in ASP.NET - The Perfect Solution的更多相关文章
- ASP.NET Core Logging Solution
Serilog.Extensions.Logging.File This package makes it a one-liner - loggerFactory.AddFile() - to con ...
- [转]Bootstrap 3.0.0 with ASP.NET Web Forms – Step by Step – Without NuGet Package
本文转自:http://www.mytecbits.com/microsoft/dot-net/bootstrap-3-0-0-with-asp-net-web-forms In my earlier ...
- .NET & C# & ASP.NET
.NET && C# && ASP.NET https://docs.microsoft.com/zh-cn/dotnet/ .NET Documentation We ...
- error_Could not load file or assembly
原文链接 Could you be missing the loaded assembly from your configuration file? Ensure you have somethin ...
- Android 自定义 ListView 显示网络上 JSON 格式歌曲列表
本文内容 环境 项目结构 演示自定义 ListView 显示网络上 JSON 歌曲列表 参考资料 本文最开始看的是一个国人翻译的文章,没有源代码可下载,根据文中提供的代码片段,自己新建的项目(比较可恶 ...
- Thinking in Java——笔记(19)
Enumerated Types Basic enum features When you create an enum, an associated class is produced for yo ...
- Cool!15个超炫的 CSS3 文本特效【上篇】
每一个网页设计师都希望创建出让用户能够赏识的网站.当然,这是不可能满足每个人的口味的.幸运的是,我们有最强大的工具和资源.实际上,我们非常多的网站模板,框架,内容管理系统,先进的工具和其他的资源可以使 ...
- Day14 summary
Since I am writing blog in Ubuntu which has not installed Chinese language package, this blog will b ...
- NodeJS 各websocket框架性能分析
For a current project at WhoScored, I needed to learn JavaScript, Node.js and WebSocket channel, aft ...
随机推荐
- HDU 3415 Max Sum of Max-K-sub-sequence 最长K子段和
链接:http://acm.hdu.edu.cn/showproblem.php?pid=3415 意甲冠军:环.要找出当中9长度小于等于K的和最大的子段. 思路:不能採用最暴力的枚举.题目的数据量是 ...
- crawler_httpclient代理访问
public String getDocumentByProxy(String url) throws ClientProtocolException, IOException { DefaultHt ...
- Python开发环境的搭建(win7)
一个.安装和配置Python 事实上,在开发python最好ubuntu环境.简单和易于扩展每个package. 在谈到如何win7建筑物Python开发环境. 因为python十字-platform ...
- BZOJ 3209 花神的数论题 数位DP+数论
题目大意:令Sum(i)为i在二进制下1的个数 求∏(1<=i<=n)Sum(i) 一道非常easy的数位DP 首先我们打表打出组合数 然后利用数位DP统计出二进制下1的个数为x的数的数量 ...
- 【高德API】如何利用MapKit开发全英文检索的iOS地图
原文:[高德API]如何利用MapKit开发全英文检索的iOS地图 制作全英文地图的展示并不困难,但是要制作全英文的数据检索列表,全英文的信息窗口,你就没办法了吧.告诉你,我有妙招!使用iOS自带的M ...
- swift 注意事项 (十六) —— 可选链
可选链(Optional Chaining) 我们都知道"可选型"是什么.那么可选链又是什么,举个样例解释一下: struct MyName{ var name } st ...
- HTML DOCTYPE 重要性
定义和使用方法 <!DOCTYPE> 声明必须是 HTML 文档的第一行.位于 <html> 标签之前. <!DOCTYPE> 声明不是 HTML 标签.它是指示 ...
- 猫学习IOS(十五)UI以前的热的打砖块游戏
猫分享.必须精品 材料代号地址:http://blog.csdn.net/u013357243/article/details/44814523 原文地址:viewmode=contents" ...
- C#yield return和yield break
C#yield return和yield break 晚上好,各位.今天结合书中所讲和MSDN所查,聊下yield关键字,它是我们简化迭代器的关键. 如果你在语句中使用了yield关键字,则意味着它在 ...
- ASP.NET 5 Overview
ASP.NET 5概观 (ASP.NET 5 Overview) http://www.asp.net/vnext/overview/aspnet-vnext/aspnet-5-overview AS ...