WebService - 使用泛型 List(of T)傳送接收大量資料
這個需求是因為有個系統的資料需要大量拋傳到我們這方來,因此開始了我的第一支Web Service,
又是一個越級打怪的情況出現,之前連寫都沒寫過,爬文過後看起來不難,於是這個美麗的錯誤就開始了。
為何會說是美麗的錯誤,因為一開始想到既然是大量資料,那就用Datatable去做接收,結果出現error message
System.InvalidOperationException: 無法序列化 DataTable
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
據網友提供的消息,只要給Datable Name就不會出現此錯誤
爬文之後發現,Web service是不能傳送Datatalbe,最後SPEC就開始使用泛型List(of T) 去接收解決這個情況。
在我個人的腦袋中是一個袋子(list),而袋子裡面放了幾本書(of T)(註一),因此傳送或接收都是收到這個袋子,
然後我再把袋子裡面的書給取出,因此我的範例就是要這些袋子裡面的書的 -書名、價格、作者、數量等資訊。
*註一:of T可以是任何一種型別(所以才稱做泛型)
我的泛型是個傳送Class的架構,如下就是我的(of T)
Public Class Storybook
Private _sbookname As String
Private _iprice As Integer
Private _sauthor As String
Private _icount As Integer
Public Property bookname() As String
Get
Return _sbookname
End Get
Set(ByVal value As String)
_sbookname = value
End Set
End Property
Public Property price() As Integer
Get
Return _iprice
End Get
Set(ByVal value As Integer)
_iprice = value
End Set
End Property
Public Property author() As String
Get
Return _sauthor
End Get
Set(ByVal value As String)
_sauthor = value
End Set
End Property
Public Property count() As Integer
Get
Return _icount
End Get
Set(ByVal value As Integer)
_icount = value
End Set
End Property
End Class
我的WebService很單純如下
Public Class TransferData
Inherits System.Web.Services.WebService
Dim dt_bookdetail As New DataTable
_
Public Function ReceiveData(ByVal booklist As List(of SStorybook)) As String
dt_bookdetail = getbookdetail(booklist)
'這裡接回的資料就depend on what u wanna do(insert to ur Database or something else)
Return dt_bookdetail.Rows.Count.ToString + " Records. Or U can Choice into to ur Database"
End Function
Private Function getbookdetail(ByVal booklist As List(Of Storybook)) As DataTable
Dim newrow As DataRow = Nothing
dt_bookdetail.Columns.Add("bookname")
dt_bookdetail.Columns.Add("price")
dt_bookdetail.Columns.Add("author")
dt_bookdetail.Columns.Add("count")
For Each Data As Storybook In booklist
newrow = dt_bookdetail.NewRow
newrow(0) = Data.bookname
newrow(1) = Data.price
newrow(2) = Data.author
newrow(3) = Data.count
dt_bookdetail.Rows.Add(newrow)
Next
Return dt_bookdetail
End Function
End Class
如此就完成了,為了確認我的web service能正常的交給對方使用,我開了一個新的page模擬
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'模擬傳送大量資料
Dim storelist As New Storybook
Dim ls As New List(Of Storybook)
For i As Integer = 0 To 10
storelist.author = "unknow"
storelist.bookname = "睡美人"
storelist.count = 100
storelist.price = 10
ls.Add(storelist)
Next
Dim senddata As New TransferData
Response.Write(senddata.ReceiveData(ls))
End Sub
瀏覽該頁面後出現如下