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 ResolveUrl
method 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 UrlEncode
d, 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. (
ResolveUrl
has 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:
public 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 ...
随机推荐
- 经典算法题每日演练——第十七题 Dijkstra算法
原文:经典算法题每日演练--第十七题 Dijkstra算法 或许在生活中,经常会碰到针对某一个问题,在众多的限制条件下,如何去寻找一个最优解?可能大家想到了很多诸如“线性规划”,“动态规划” 这些经典 ...
- SQL2005性能分析一些细节功能你是否有用到?
原文:SQL2005性能分析一些细节功能你是否有用到? 我相信很多朋友对现在越来越大的数据量而感到苦恼,可是总要面对现实啊,包括本人在内的数据库菜鸟们在开发B/S程序时,往往只会关心自己的数据是否正确 ...
- C# - Recommendations for Abstract Classes vs. Interfaces
The choice of whether to design your functionality as an interface or an abstract class can somet ...
- MySql状态查看方法 MySql如何查看连接数和状态?
原文:MySql状态查看方法 MySql如何查看连接数和状态? 如果是root帐号,你能看到所有用户的当前连接.如果是其它普通帐号,只能看到自己占用的连接 怎么进入mysql命令行呢? mysql的安 ...
- Effective C++:规定34:区分接口继承和实现继承
(一个) class Shape { public: virtual void draw() const = 0; virtual void error(const string& msg); ...
- Asp.Net MVC4 + Oracle + EasyUI + Bootstrap 1
Asp.Net MVC4 + Oracle + EasyUI + Bootstrap 序章 Asp.Net MVC4 + Oracle + EasyUI + Bootstrap 序章 -- 新建微软实 ...
- 判断文件是否存在,不存在创建文件&&判断文件夹是否存在,不存在创建文件夹
1.判断文件是否存在,不存在创建文件 File file=new File("C:\\Users\\QPING\\Desktop\\JavaScript\\2.htm"); if( ...
- PHP 做 RSA 签名 生成订单(支付宝例子)
/组合签名 $a=time(); $b=substr($a, 1); //生成随机订单号 $orderid= $b.mt_rand(10000,99999); //合作身份者id,以2088开头的16 ...
- Android设备连接Unity Profiler性能分析器
Unity提供两种方式让Developer的Android设备连接Profiler进行性能分析: 1.通过wifi,Android设备和计算机处于同一个Wlan中. 2.通过USB ADB 普通情况我 ...
- location将地址栏参数拆分成键值对的对象
window.location可获取地址栏的一系列信息,并且每个浏览器都支持该属性,非常方便.而获取到的问号后面的参数可以进行加工转变成我们所想要的键值对. location的属性: 属性名 例子 说 ...