iT邦幫忙

DAY 1
6

ASP.NET技巧系列 第 1

動態的設定WebService的網址

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

下一篇
ASP.NET 2.0 使用資料表動態產生TreeView的樹狀結構 Part1
系列文
ASP.NET技巧17
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
pantc328
iT邦高手 1 級 ‧ 2009-10-05 09:02:48

這種我都設在App.Config or Web.Config裡

我要留言

立即登入留言