找不到VB.Net MasterPage Page.PreLoad属性

问题描述 投票:0回答:1

我正在尝试使用Microsoft .Net ViewStateUserKey和Double Submit Cookie实现跨站点请求伪造(CSRF)。欲了解更多信息,请访问这个link

上面的代码是在C#中,我将其转换为VB.Net。现在的问题是,在这段代码中有一条线

Page.PreLoad += master_Page_PreLoad;

当我尝试在VB.Net中转换相同的行时,它没有找到任何这样的事件Page.PreLoad

请帮忙我该怎么做。

谢谢

c# vb.net cookies csrf master-pages
1个回答
0
投票

转换为VB的C#Master Page模板如下所示:

Partial Class MasterPage
    Inherits System.Web.UI.MasterPage

    Private Const AntiXsrfTokenKey As String = "__AntiXsrfToken"
    Private Const AntiXsrfUserNameKey As String = "__AntiXsrfUserName"
    Private _antiXsrfTokenValue As String

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
        Dim requestCookie = Request.Cookies(AntiXsrfTokenKey)
        Dim requestCookieGuidValue As Guid

        If requestCookie IsNot Nothing AndAlso Guid.TryParse(requestCookie.Value, requestCookieGuidValue) Then
            _antiXsrfTokenValue = requestCookie.Value
            Page.ViewStateUserKey = _antiXsrfTokenValue
        Else
            _antiXsrfTokenValue = Guid.NewGuid().ToString("N")
            Page.ViewStateUserKey = _antiXsrfTokenValue
            Dim responseCookie = New HttpCookie(AntiXsrfTokenKey) With {
                .HttpOnly = True,
                .Value = _antiXsrfTokenValue
            }

            If FormsAuthentication.RequireSSL AndAlso Request.IsSecureConnection Then
                responseCookie.Secure = True
            End If

            Response.Cookies.[Set](responseCookie)
        End If

        AddHandler Page.PreLoad, AddressOf master_Page_PreLoad
    End Sub

    Protected Sub master_Page_PreLoad(ByVal sender As Object, ByVal e As EventArgs)
        If Not IsPostBack Then
            ViewState(AntiXsrfTokenKey) = Page.ViewStateUserKey
            ViewState(AntiXsrfUserNameKey) = If(Context.User.Identity.Name, String.Empty)
        Else

            If CStr(ViewState(AntiXsrfTokenKey)) <> _antiXsrfTokenValue OrElse CStr(ViewState(AntiXsrfUserNameKey)) <> (If(Context.User.Identity.Name, String.Empty)) Then
                Throw New InvalidOperationException("Validation of Anti-XSRF token failed.")
            End If
        End If
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    End Sub
End Class

我相信你要找的具体线路是AddHandler Page.PreLoad, AddressOf master_Page_PreLoad

为了将来参考,如果你想将C#代码转换为VB,反之亦然,那么可以在这里找到一个非常棒的Telerik工具:http://converter.telerik.com/。为了获得我上面发布的代码,我只是在那里运行C#模板。

© www.soinside.com 2019 - 2024. All rights reserved.