2013-02-14 2 views
0

После записывается мой код в vb.net.возвращает расширение OpenIdButton в нуль

Protected Sub OpenIdButton3_LoggedIn (ByVal отправитель As Object, ByVal е Как DotNetOpenAuth.OpenId.RelyingParty.OpenIdEventArgs) Ручки OpenIdButton3.LoggedIn

OpenIdButton3.Visible = False

дим профиль, как ClaimsResponse = е. Response.GetExtension (Of ClaimsResponse)()

Dim электронной почты As String = profile.Email

MsgBox (электронная почта)

End Sub

Но линия

Dim электронная почта As String = profile.Email

дает следующую ошибку.

Сведения об исключении: System.NullReferenceException: Ссылка на объект не установлена ​​в экземпляр объекта.

Я прочитал соответствующую документацию по этому вопросу, и я внедрил AXFetchAsSregTransform в webconfig. Ниже приведен блок, который показывает то же самое.

<sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core"> 
    <section name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection" requirePermission="false" allowLocation="true" /> 
    <section name="openid" type="DotNetOpenAuth.Configuration.OpenIdElement, DotNetOpenAuth.OpenId" requirePermission="false" allowLocation="true" /> 
    <section name="oauth" type="DotNetOpenAuth.Configuration.OAuthElement, DotNetOpenAuth.OAuth" requirePermission="false" allowLocation="true" /> 
    <section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" /> 
    <section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" /> 
</sectionGroup> 

> < dotNetOpenAuth>

<openid> 

    <relyingParty> 

 <add type="DotNetOpenAuth.OpenId.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth" /> 

    </behaviors> 

    </relyingParty> 

</openid> 

</dotNetOpenAuth>

Даже тогда, я, кажется, чтобы получить нулевое значение. Я получаю аутентификацию от Google.

Может ли кто-нибудь помочь мне в этом?

ответ

0

Наконец, я нашел решение. Отправьте его сюда, чтобы помочь другим, кому грозит такая же проблема.

«Глобальная декларация - Если вы объявляете их на местном уровне, по какой-то причине, они не похоже на работу

Dim relyingParty Как Новый OpenIdRelyingParty

Dim authResponse Как IAuthenticationResponse

После объявления об этом создайте кнопку в своей веб-форме, которая позволит пользователю войти в Google. И макет, на котором будет отображаться идентификатор электронной почты пользователя, который вошёл в систему.

«Наведите следующий код на загрузку страницы.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
    Dim googleAppsDiscovery As New HostMetaDiscoveryService() With {.UseGoogleHostedHostMeta = True} 
    relyingParty.DiscoveryServices.Insert(0, googleAppsDiscovery) 

    authResponse = relyingParty.GetResponse() 

    If authResponse IsNot Nothing Then 
     If authResponse.Status = AuthenticationStatus.Authenticated Then 
      Dim fetch As FetchResponse = authResponse.GetExtension(Of FetchResponse)() 
      If fetch IsNot Nothing Then 
       ' Save user details in session variables 
       'Dim temp As [String]() = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email).ToString().Split("@"c) 
       Dim temp As String = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email).ToString() 
       If temp IsNot Nothing Then 
        Dim userName As String = temp 
        Label1.Text = "You are logged in as : " & userName 
       End If 
      End If 
     End If 
    End If 
End Sub 

Put следующий код в события нажатия кнопки

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click 
    Dim currentPageURL As String = curPageURL.ToString 

    Dim urlRealm As New Uri(currentPageURL) 
    Dim urlReturn As New Uri(currentPageURL) 

    Dim rm As Realm = New Realm(urlRealm) 
    Dim gIdentifier As String = "https://www.google.com/accounts/o8/id" 

    Dim request As IAuthenticationRequest = relyingParty.CreateRequest(gIdentifier, urlRealm, urlReturn) 

    Dim fetch As New FetchRequest 

    fetch.Attributes.Add(New AttributeRequest(WellKnownAttributes.Contact.Email, True)) 
    request.AddExtension(fetch) 

    request.RedirectToProvider() 
End Sub 

добавьте следующие две функции, чтобы получить поле Ваш текущий URL-адрес

Function curPageURL() As String 
    Dim s, protocol, port As String 

    If Request.ServerVariables("HTTPS") = "on" Then 
     s = "s" 
    Else 
     s = "" 
    End If 

    protocol = strLeft(LCase(Request.ServerVariables("SERVER_PROTOCOL")), "/") & s 

    If Request.ServerVariables("SERVER_PORT") = "80" Then 
     port = "" 
    Else 
     port = ":" & Request.ServerVariables("SERVER_PORT") 
    End If 

    curPageURL = protocol & "://" & Request.ServerVariables("SERVER_NAME") & _ 
      port & Request.ServerVariables("SCRIPT_NAME") 
End Function 

Function strLeft(ByVal str1 As String, ByVal str2 As String) As String 
    strLeft = Left(str1, InStr(str1, str2) - 1) 
End Function 

И вы сделали.

Смежные вопросы