ASP.Net: Using System.Web.UI.Control.ResolveUrl() in a shared/static function

萝らか妹 提交于 2019-11-28 19:48:12

问题


What is the best way to use ResolveUrl() in a Shared/static function in Asp.Net? My current solution for VB.Net is:

Dim x As New System.Web.UI.Control
x.ResolveUrl("~/someUrl")

Or C#:

System.Web.UI.Control x = new System.Web.UI.Control();
x.ResolveUrl("~/someUrl");

But I realize that isn't the best way of calling it.


回答1:


I use System.Web.VirtualPathUtility.ToAbsolute.




回答2:


It's worth noting that although System.Web.VirtualPathUtility.ToAbsolute is very useful here, it is not a perfect replacement for Control.ResolveUrl.

There is at least one significant difference: Control.ResolveUrl handles Query Strings very nicely, but they cause VirtualPathUtility to throw an HttpException. This can be absolutely mystifying the first time it happens, especially if you're used to the way that Control.ResolveUrl works.

If you know the exact structure of the Query String you want to use, this is easy enough to work around, viz:

public static string GetUrl(int id)
{
    string path = VirtualPathUtility.ToAbsolute("~/SomePage.aspx");
    return string.Format("{0}?id={1}", path, id);
}

...but if the Query String is getting passed in from an unknown source then you're going to need to parse it out somehow. (Before you get too deep into that, note that System.Uri might be able to do it for you).




回答3:


I tend to use HttpContext.Current to get the page, then run any page/web control methods off that.



来源:https://stackoverflow.com/questions/26796/asp-net-using-system-web-ui-control-resolveurl-in-a-shared-static-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!