【问题标题】:Trying to return data from the asp.net web api尝试从 asp.net web api 返回数据
【发布时间】:2012-05-18 22:32:58
【问题描述】:

我正在尝试将 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

【问题讨论】:

  • 尝试返回dt.AsEnumerable()
  • 嗨 - 不幸的是,这也不起作用 - 异常显示:无法转换类型为“System.Data.EnumerableRowCollection1[System.Data.DataRow]' to type 'System.Collections.Generic.IEnumerable1[System.Web.UI.WebControls.Table]”的对象.再次感谢,马克

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    问题在于你的函数的签名。

    Public Function GetValues() As IEnumerable(Of Table)
    

    应该是这样的

    Public Function GetValues() As IEnumerable(Of DataTable)
    

    【讨论】:

    • 嗨 - 谢谢你的建议 - 我改变了它,当前的错误提示:无法转换类型为“System.Data.EnumerableRowCollection1[System.Data.DataRow]' to type 'System.Collections.Generic.IEnumerable1[System.Data.DataTable]”的对象。 - 谢谢
    • 尝试使用 IEnumerable(Of DataRow) 作为这个真正的底层类型
    猜你喜欢
    • 1970-01-01
    • 2013-06-23
    • 2017-05-28
    • 2015-01-05
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多