C# ASP.Net:在共享/静态函数中使用 System.Web.UI.Control.ResolveUrl()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.Net: Using System.Web.UI.Control.ResolveUrl() in a shared/static function
提问by travis
What is the best way to use ResolveUrl() in a Shared/static function in Asp.Net? My current solution for VB.Net is:
在 Asp.Net 的共享/静态函数中使用 ResolveUrl() 的最佳方法是什么?我目前对 VB.Net 的解决方案是:
Dim x As New System.Web.UI.Control
x.ResolveUrl("~/someUrl")
Or C#:
或 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.
但我意识到这不是最好的称呼方式。
采纳答案by Dave Ward
回答by Keith
I tend to use HttpContext.Current to get the page, then run any page/web control methods off that.
我倾向于使用 HttpContext.Current 来获取页面,然后运行任何页面/网络控制方法。
回答by jdw
It's worth noting that although System.Web.VirtualPathUtility.ToAbsolute is very useful here, it is nota perfect replacement for Control.ResolveUrl.
值得注意的是,虽然 System.Web.VirtualPathUtility.ToAbsolute 在这里非常有用,但它并不是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.
至少有一个显着差异:Control.ResolveUrl 非常好地处理查询字符串,但它们会导致 VirtualPathUtility 抛出 HttpException。这在第一次发生时绝对令人困惑,特别是如果您习惯了 Control.ResolveUrl 的工作方式。
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).
...但是如果查询字符串是从未知来源传入的,那么您将需要以某种方式解析它。(在深入了解之前,请注意 System.Uri 可能会为您完成)。