ASP.net - 从类声明中获取页面虚拟页面

时间:2014-09-18 19:53:39

标签: c# asp.net vb.net

我正在尝试获取类的VirtualPath。 当实例化类时,我可以调用this.AppRelativeVirtualPath;(或者在VB Me.AppRelativeVirtualPath中),它会给我“〜/ content / page.aspx”。

现在,我需要调用THE CLASS而不是实例来获取该路径。像这样:

public class Page : System.Web.UI.Page
{
    public static string GetPath() { return Page.AppRelativeVirtualPath; }
}

但我不能这样做,因为“AppRelativeVirtualPath”是非共享方法。 叫它的方法是什么?

我需要的东西能给我带来与此相同的结果:http://msdn.microsoft.com/pt-br/library/system.web.ui.templatecontrol.apprelativevirtualpath(v=vs.110).aspx

在TIM'S ANSEER之后编辑

我使用他的代码编写的特定类是这样的:

Namespace Web.Pages
    Public Class Dir
        Inherits System.Web.UI.Page
        Public Shared Function GetPath() As String
            Dim page As Web.Pages.Dir = TryCast(System.Web.HttpContext.Current.Handler, Web.Pages.Dir)
            If (Page Is Nothing) Then Return "" Else Return page.AppRelativeVirtualPath
        End Function
    End Class
End Namespace

那(我想要解决的地方):

Namespace Web.Pages
    Public Class MainPage
        Inherits System.Web.UI.Page
        Public ReadOnly Property LinkToDir() As String
            Get
                Return Web.Pages.Dir.GetPath()
            End Get
        End Property
    End Class
End Namespace

请参阅,上下文是在“MainPage”上调用“Dir”页面上的静态方法(“Dir”)返回它的ASP页面虚拟地址(即“〜/ content / dir.aspx”) )。

我如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

您可以使用HttpContext.Current.Handler从静态/共享上下文中获取页面实例:

public static string GetPath() 
{  
    Page page = HttpContext.Current.Handler as Page;
    if (page != null)
        return page.AppRelativeVirtualPath;
    return null;
}

VB.NET:

Public Shared Function GetPath() As String
    Dim page = TryCast(HttpContext.Current.Handler, Page)
    If page IsNot Nothing Then
        Return page.AppRelativeVirtualPath
    Else
        Return Nothing
    End If
End Function