If you are looking for ResolveUrl outside of Page/Control, and even if you are not, this is for you.

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:

  1. When the URL begins with a slash (either / or \), it will not touch it!
  2. When the URL begins with ~/, it will replace it with the AppVirtualPath.
  3. When the URL is an absolute URL, it will not touch it. (ResolveUrl has a bug with this, as I said before...)
  4. In any other case (even beginning with ~, but not slash), it will append the URL to the AppVirtualPath.
  5. 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 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的更多相关文章

  1. ASP.NET Core Logging Solution

    Serilog.Extensions.Logging.File This package makes it a one-liner - loggerFactory.AddFile() - to con ...

  2. [转]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 ...

  3. .NET & C# & ASP.NET

    .NET && C# && ASP.NET https://docs.microsoft.com/zh-cn/dotnet/ .NET Documentation We ...

  4. error_Could not load file or assembly

    原文链接 Could you be missing the loaded assembly from your configuration file? Ensure you have somethin ...

  5. Android 自定义 ListView 显示网络上 JSON 格式歌曲列表

    本文内容 环境 项目结构 演示自定义 ListView 显示网络上 JSON 歌曲列表 参考资料 本文最开始看的是一个国人翻译的文章,没有源代码可下载,根据文中提供的代码片段,自己新建的项目(比较可恶 ...

  6. Thinking in Java——笔记(19)

    Enumerated Types Basic enum features When you create an enum, an associated class is produced for yo ...

  7. Cool!15个超炫的 CSS3 文本特效【上篇】

    每一个网页设计师都希望创建出让用户能够赏识的网站.当然,这是不可能满足每个人的口味的.幸运的是,我们有最强大的工具和资源.实际上,我们非常多的网站模板,框架,内容管理系统,先进的工具和其他的资源可以使 ...

  8. Day14 summary

    Since I am writing blog in Ubuntu which has not installed Chinese language package, this blog will b ...

  9. NodeJS 各websocket框架性能分析

    For a current project at WhoScored, I needed to learn JavaScript, Node.js and WebSocket channel, aft ...

随机推荐

  1. Canvas旋转图片--保持相同大小的算法

     function drawImg(angle) {     canvas.width = canvas.width; var distance = size / 2 * Math.sqrt(2) ...

  2. ArcGIS网络分析之Silverlight客户端最近设施点分析(四)

    原文:ArcGIS网络分析之Silverlight客户端最近设施点分析(四) 在上一篇中说了如何实现最近路径分析,本篇将讨论如何实现最近设施点分析. 最近设施点分析实际上和路径分析有些相识,实现的过程 ...

  3. Android - 视图Android应用(apk)签名

    视图Android应用(apk)签名 本文地址: http://blog.csdn.net/caroline_wendy 在微博.微信开放平台注冊应用时,须要填写应用(apk)的签名,能够使用keyt ...

  4. jQuery实现按键盘方向键翻页

    1.jQuery代码: $(document).ready(function(){ var prevpage=$("#pre").attr("href"); v ...

  5. sqlserver备份的几种方式

    1.用sqlserver的维护计划 在这里我就不给截图演示了,这个比较简单,无非就是通过sqlserver自己的维护计划拖拽出2个一个‘备份数据库’任务和一个‘清除维护’任务. 需要注意的点: 1)有 ...

  6. C#yield return和yield break

    C#yield return和yield break 晚上好,各位.今天结合书中所讲和MSDN所查,聊下yield关键字,它是我们简化迭代器的关键. 如果你在语句中使用了yield关键字,则意味着它在 ...

  7. PHP 9: 表达式

    原文:PHP 9: 表达式 本章介绍PHP的表达式.PHP的表达式其实和其他语言没有什么区别.普通的赋值是表达式,函数也是表达式,通过函数赋值也是.三元条件运算符也是,即: $first ? $sec ...

  8. 利用PhantomJS进行网页截屏

    利用PhantomJS进行网页截屏 关于PhantomJS PhantomJS 是一个基于WebKit的服务器端 JavaScript API.它全面支持web而不需浏览器支持,其快速,原生支持各种W ...

  9. 如何通过js给QQ好友发送信息

    一般我们在做页面活动的时候可能会碰到点击一个按钮把一些相关的信息通过QQ发送给你的好友,这种信息推送的功能该如何实现呢!下面我来介绍下使用方法! 代码如下: <!DOCTYPE HTML> ...

  10. Scala很难!

    Scala很难! 本文是从 Yes, Virginia, Scala is hard 这篇文章翻译而来. 首先要说的是,我是一个Scala粉丝,我作为一个Scala语言的倡导者差不多有5年历史了.我写 ...