如何从 asp.net Page_Load 中的响应 HttpWebResponse 更新 asp:label?

How to Update asp:label from the response HttpWebResponse in asp.net Page_Load?

我是 vb.net 和 asp.net 的新手。我正在尝试更新 asp: Page_Load 中的标签。标签的值全部来自一个Webservice。

vb.net 代码:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then lblMaxValue.Text = " Value is: " & GetRequestResponse(URL)

服务代码:

Private Sub GetRequestResponse(uri As Uri, callback As Action(Of String))
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
    Dim request As HttpWebRequest = DirectCast(HttpWebRequest.Create(uri), HttpWebRequest)

    request.Method = "GET"
    request.ContentType = "application/json"

    request.BeginGetResponse(
        Function(x)
            Using response As HttpWebResponse = DirectCast(request.EndGetResponse(x), HttpWebResponse)
                If callback IsNot Nothing Then

                    Dim reader As New StreamReader(response.GetResponseStream())
                    Dim streamText As String = reader.ReadToEnd()
                    callback(streamText)
                End If
            End Using
            Return 1
        End Function, Nothing)
End Sub

没有错误,但值没有更新。

部分选项:

  1. 让它同步;或
  2. 使用脚本管理器、更新面板、计时器和会话变量;或
  3. 如下使用 AddOnPreRenderCompleteAsync(以及进一步 described here):

aspx 页面:

<%@ Page Language="VB" Async="true" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="lblMaxValue" runat="server" Text="Label"></asp:Label>
        </div>
    </form>
</body>
</html>

隐藏代码:

Imports System.Net
Imports System.IO

Partial Class Default2
    Inherits System.Web.UI.Page

    Private _request As HttpWebRequest

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Dim uri As New Uri("http://api.open-notify.org/astros.json")
            _request = HttpWebRequest.Create(uri)
            AddOnPreRenderCompleteAsync(New BeginEventHandler(AddressOf GetRequestResponse), New EndEventHandler(AddressOf EndAsyncOperation))
        End If
    End Sub
    Protected Function GetRequestResponse(ByVal sender As Object, ByVal e As EventArgs, ByVal cb As AsyncCallback, ByVal state As Object) As IAsyncResult
        Return _request.BeginGetResponse(cb, state)
    End Function

    Private Sub EndAsyncOperation(ByVal ar As IAsyncResult)
        Dim text As String

        Using response As WebResponse = _request.EndGetResponse(ar)

            Using reader As StreamReader = New StreamReader(response.GetResponseStream())
                text = reader.ReadToEnd()
            End Using
        End Using

        lblMaxValue.Text = " Value is: " & text
    End Sub

End Class