简体   繁体   English

ASP.Net:在共享/静态函数中使用 System.Web.UI.Control.ResolveUrl()

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

What is the best way to use ResolveUrl() in a Shared/static function in Asp.Net?在 Asp.Net 的共享/静态函数中使用 ResolveUrl() 的最佳方法是什么? My current solution for VB.Net is:我目前对 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.但我意识到这不是最好的称呼方式。

It's worth noting that although System.Web.VirtualPathUtility.ToAbsolute is very useful here, it is not a 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.至少有一个显着差异:Control.ResolveUrl 非常好地处理查询字符串,但它们会导致 VirtualPathUtility 抛出 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 的工作方式。

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 可能会为您完成)。

我倾向于使用 HttpContext.Current 来获取页面,然后运行任何页面/网络控制方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM