動態的設定WebService的網址

動態的設定WebService的網址

使用WebService很方便,透過【加入Web參考】的方式來為我的專案加入WebService。不過由於系統開發過程中,小喵會區分為測試主機與正式主機,因此每次系統要上線的時候,就需要把WebService的參考Server改變。

這讓小喵開始構思,是否可以動態的告訴WebService應該到哪台Server去啟用執行WebService呢。再進一步,如果我將使用哪一台WebService設定抽離出來,變成一個設定檔。那麼我只需要在測試台與正式台使用不同的設定檔。但是程式卻是可以一致的。

假設我

測試環境要去使用 http://localhost/topcat/myWebService.asmx

正式環境要去使用http://blueshop.com.tw/topcat/myWebService.asmx

我先寫一個讀取設定檔的Function如下,設定檔中主要是記錄Server名稱或IP


    Private Function GetWSUrl() As String
        Dim StrmRd As New StreamReader("WebServiceUrl.ini")
        Dim Line As String = ""
        Dim WSUrl As String = ""
        Try
            Do
                Line = StrmRd.ReadLine()
                If Line <> "" Then
                    WSUrl += Line
                End If
            Loop Until Line Is Nothing
            GetWSUrl = WSUrl

        Catch ex As Exception
            Throw New Exception(ex.Message.ToString)

        Finally
            StrmRd.Close()
            StrmRd.Dispose()
            StrmRd = Nothing

        End Try
    End Function

 

然後我就可以再調用WebService的時候

Try
    Using obj As New WebReference.PSNDRobot
        obj.Url = "http://" & GetWSUrl() & "/MyWebService.asmx" '在此動態設定WebService
        obj.Discover()  '重新整理WebService
        Dim Rc as String = obj.Test()
    End Using

Catch ex As Exception
    Throw New Exception(ex.Message)
End Try


 

 

 


以下是簽名:


Microsoft MVP
Visual Studio and Development Technologies
(2005~2019/6) 
topcat
Blog:http://www.dotblogs.com.tw/topcat