试图从asp.net web api返回数据

时间:2012-05-18 22:32:59

标签: asp.net asp.net-web-api

我正在尝试将web api添加到现有的asp.net ASPX站点。

我想要的是它返回(以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

2 个答案:

答案 0 :(得分:2)

我认为答案只是将您的函数签名更改为As EnumerableRowCollection。当你获取一个DataTable对象并使用AsEnumerable()方法时,它会将一个数据行集合作为EnumerableRowCollection返回,尽管将它写成EnumerableRowCollection就足够了。

答案 1 :(得分:0)

查看异常消息,它说它无法将DataRow集合转换为System.Web.UI.WebControls.Table的IEnumerable。

问题是你的功能的签名。

Public Function GetValues() As IEnumerable(Of Table)

应该是

Public Function GetValues() As IEnumerable(Of DataTable)