【问题标题】:ASP.net - Get Page VirtualPage from Class DeclarationASP.net - 从类声明中获取页面 VirtualPage
【发布时间】:2014-09-18 19:53:38
【问题描述】:

我正在尝试获取类的类 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 的回答之后进行编辑

我用他的代码写的具体类是这样的:

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” )。

我怎样才能做到这一点?

【问题讨论】:

    标签: c# asp.net vb.net


    【解决方案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
    

    【讨论】:

    • 没用。 “GetPath()”函数一直不返回任何内容。
    • @SammuelMiranda:你从哪里称呼它?它必须来自实际的页面生命周期。
    • 不,我需要从另一个页面调用它 - 活动页面调用另一个类的静态方法(这也是一个页面,但尚未上线)。
    • @SammuelMiranda:那么它不应该返回 null,因为“活动”页面将是 HttpContext.Current.Handler。你用过调试器吗?
    • 是的 - 您编写的函数没有给出错误,但它总是落在“ELSE”部分(返回 NOTHING)。因为 PAGE 没有从 trycast 中返回
    猜你喜欢
    • 1970-01-01
    • 2022-10-21
    • 2017-06-19
    • 2013-11-26
    • 2019-05-18
    • 2018-06-16
    • 2021-07-24
    • 2016-06-29
    • 2022-01-19
    相关资源
    最近更新 更多