将委托函数从c#转换为vb.net以用于Google OAuth 2的问题

本文关键字:Google 用于 OAuth 问题 net vb 函数 转换 | 更新日期: 2023-09-27 18:28:23

我一直在尝试为一位同事的项目将Google OAuth 2示例从C#转换为Vb.net。我在翻译以下方法时遇到了很多问题:

    private OAuth2Authenticator<WebServerClient> CreateAuthenticator()
        {
            // Register the authenticator.
            var provider = new WebServerClient(GoogleAuthenticationServer.Description);
            provider.ClientIdentifier = ClientCredentials.ClientID;
            provider.ClientSecret = ClientCredentials.ClientSecret;
            var authenticator = 
                new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization) { NoCaching = true };
            return authenticator;
        }
        private IAuthorizationState GetAuthorization(WebServerClient client)
        {
            // If this user is already authenticated, then just return the auth state.
            IAuthorizationState state = AuthState;
            if (state != null)
            {
                return state;
            }
            // Check if an authorization request already is in progress.
            state = client.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request));
            if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken)))
            {
                // Store and return the credentials.
                HttpContext.Current.Session["AUTH_STATE"] = _state = state;
                return state;
            }
            // Otherwise do a new authorization request.
            string scope = TasksService.Scopes.TasksReadonly.GetStringValue();
            OutgoingWebResponse response = client.PrepareRequestUserAuthorization(new[] { scope });
            response.Send(); // Will throw a ThreadAbortException to prevent sending another response.
            return null;
        }

主要问题是这条线:

var authenticator = new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization) { NoCaching = true };

此特定行的方法签名如下所示:

Public Sub New(tokenProvider As TClient, authProvider As System.Func(Of TClient, DotNetOpenAuth.OAuth2.IAuthorizationState))

我对VB.net中的Delegate函数的理解并不是最好的。然而,我已经阅读了所有MSDN文档和网络上的其他相关资源,但我仍然不知道如何翻译这一行。

到目前为止,我的所有尝试都导致了强制转换错误(见下文)或并没有调用GetAuthorization。

代码(.net 3.5上的vb.net)

    Private Function CreateAuthenticator() As OAuth2Authenticator(Of WebServerClient)
        ' Register the authenticator.
        ' Register the authenticator.
        Dim provider = New WebServerClient(GoogleAuthenticationServer.Description, oauth.ClientID, oauth.ClientSecret)
        'GetAuthorization isn't called
        'Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(provider, AddressOf GetAuthorization) With {.NoCaching = True}
        'This works, but results in type error
        Dim authDelegate As Func(Of WebServerClient, IAuthorizationState) = AddressOf GetAuthorization
        Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(provider, authDelegate) With {.NoCaching = True}
        'This works, but results in type error
        'Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(provider, GetAuthorization(provider)) With {.NoCaching = True}
        'GetAuthorization isn't called
        'Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(provider, New Func(Of WebServerClient, IAuthorizationState)(Function(c) GetAuthorization(c))) With {.NoCaching = True}
        'Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(provider, New Func(Of WebServerClient, IAuthorizationState)(AddressOf GetAuthorization)) With {.NoCaching = True}
        Return authenticator
    End Function

    Private Function GetAuthorization(arg As WebServerClient) As IAuthorizationState
        ' If this user is already authenticated, then just return the auth state.
        Dim state As IAuthorizationState = AuthState
        If (Not state Is Nothing) Then
            Return state
        End If
        ' Check if an authorization request already is in progress.
        state = arg.ProcessUserAuthorization(New HttpRequestInfo(HttpContext.Current.Request))
        If (state IsNot Nothing) Then
            If ((String.IsNullOrEmpty(state.AccessToken) = False Or String.IsNullOrEmpty(state.RefreshToken) = False)) Then
                ' Store Credentials
                HttpContext.Current.Session("AUTH_STATE") = state
                _state = state
                Return state
            End If
        End If
        ' Otherwise do a new authorization request.
        Dim scope As String = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue()
        Dim _response As OutgoingWebResponse = arg.PrepareRequestUserAuthorization(New String() {scope})
        ' Add Offline Access and forced Approval
        _response.Headers("location") += "&access_type=offline&approval_prompt=force"
        _response.Send() ' Will throw a ThreadAbortException to prevent sending another response.
        Return Nothing
    End Function

投射错误

Server Error in '/' Application.
Unable to cast object of type 'DotNetOpenAuth.OAuth2.AuthorizationState' to type 'System.Func`2[DotNetOpenAuth.OAuth2.WebServerClient,DotNetOpenAuth.OAuth2.IAuthorizationState]'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Unable to cast object of type 'DotNetOpenAuth.OAuth2.AuthorizationState' to type 'System.Func`2[DotNetOpenAuth.OAuth2.WebServerClient,DotNetOpenAuth.OAuth2.IAuthorizationState]'.

我花了一天的大部分时间在这上面,它开始让我发疯。非常感谢您的帮助。

更新

我没有提到,我已经尝试了所有可用的在线C#到VB.net的代码转换。所有结果都会导致以下有问题的线路转换:

Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(provider, AddressOf GetAuthorization) With {.NoCaching = True}

这导致GetAuthorization方法未被调用。

将委托函数从c#转换为vb.net以用于Google OAuth 2的问题

转换器产生的代码行,以及其他不抛出异常的解决方案,看起来都很好。如果转换该行代码时出现问题,则会出现异常或错误。这意味着问题在代码的其他地方,可能在OAuth2Authenticator(T)构造函数中。

你的同事是否可以简单地使用对库的引用(二进制或项目),这样你就不必转换代码了?

要将代码从一种语言翻译成另一种语言,请尝试使用伟大的工具SharpDevelop。该工具是MS VS 2008的免费替代品,您可以在C#、VB.NET、IronPython和Boo语言之间进行翻译