我試圖將web api添加到現有的asp.net ASPX站點。試圖從asp.net web api返回數據
所有我想要的是爲它返回(以JSON或XML)我的查詢結果 - 但是我得到的錯誤:無法投入'System.Data.DataTable'類型的對象鍵入'System.Collections。 Generic.IEnumerable`1 [System.Web.UI.WebControls.Table]」。
...在代碼的最後部分。
我在API控制器代碼:
Imports System.Web.Http
Imports System.Web
Imports System.Data
Imports System.Data.SqlClient
Public Class ValuesController
Inherits ApiController
' GET /api/<controller>
Public Function GetValues() As IEnumerable(Of Table)
Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=inv;Integrated Security=True")
Dim cmd As SqlCommand = New SqlCommand("select * from customers", con)
cmd.CommandType = CommandType.Text
Dim adapter As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim dt As New DataTable
Using con
Try
con.Open()
adapter.Fill(dt)
'Check if any rows were returned
If dt.Rows.Count = 0 Then
'If no rows, return nothing
Return Nothing
Else
'Return the filled datatable
Return dt
End If
Catch ex As Exception
con.Close()
Throw ex
Finally
con.Close()
End Try
End Using
Return New String() {"value1", "value2"}
End Function
嘗試返回dt.AsEnumerable() – Brij
嗨 - 不幸的是,也沒有工作 - 異常顯示:無法投型'System.Data.EnumerableRowCollection'1 [System.Data.DataRow]類型的對象類型'System.Collections.Generic.IEnumerable'1 [System.Web.UI.WebControls.Table]'。再次感謝,馬克 – Mark