JsonMediaTypeFormatter.WriteToStreamAsync,“连接未打开”?

时间:2014-10-02 13:25:27

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

我正在使用VB开发一个Web Api项目,在尝试从我的服务中读取响应时出现了一个奇怪的错误。

以下是使用的代码,如果您需要更多信息,请与我们联系。

我正在使用实体框架。

这是输出日志:

Message='Action returned 'System.Collections.Generic.List`1[DimSuporteModelo.Sistema]'',         Operation=ReflectedHttpActionDescriptor.ExecuteAsync
iisexpress.exe Information: 0 : Message='Will use same 'JsonMediaTypeFormatter' formatter',   Operation=JsonMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message='Selected formatter='JsonMediaTypeFormatter', content-    type='application/json; charset=utf-8'', Operation=DefaultContentNegotiator.Negotiate
iisexpress.exe Information: 0 : Operation=ApiControllerActionInvoker.InvokeActionAsync,     Status=200 (OK)
iisexpress.exe Information: 0 : Operation=SistemaController.ExecuteAsync, Status=200 (OK)
iisexpress.exe Information: 0 : Response, Status=200 (OK), Method=GET, Url=http://localhost:2421/api/Sistema/True/1, Message='Content-type='application/json; charset=utf-8', content-length=unknown'
'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/12/ROOT-1-130567283533102096): Loaded     'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Design\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Desig    n.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is     enabled.
iisexpress.exe Error: 0 : Operation=JsonMediaTypeFormatter.WriteToStreamAsync,     Exception=System.InvalidOperationException: The connection is not open.
   at System.Data.EntityClient.EntityConnection.get_ServerVersion()
   at GetServerVersion(Object )
   at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)
iisexpress.exe Information: 0 : Message='Will use same 'JsonMediaTypeFormatter' formatter',     Operation=JsonMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message='Selected formatter='JsonMediaTypeFormatter', content-    type='application/json; charset=utf-8'', Operation=DefaultContentNegotiator.Negotiate
iisexpress.exe Information: 0 : Operation=JsonMediaTypeFormatter.WriteToStreamAsync
iisexpress.exe Information: 0 : Operation=SistemaController.Dispose
A first chance exception of type 'System.AggregateException' occurred in mscorlib.dll

以下是调用web api的代码:

Public Overloads Shared Function GetObjetos(Of T)(servico As String, ativo As Boolean, idCliente As Integer)
        Dim parametros As String = ""
        parametros = String.Format("/{0}/{1}", ativo, idCliente)
        Dim resposta As HttpResponseMessage = clienteHttp.GetAsync(UriServico & servico & parametros).Result
        Return resposta.Content.ReadAsAsync(Of List(Of T)()).Result
    End Function

这是控制器:

Public Function GetSistemas(ativo As String, id As Integer) As List(Of DimSuporteModelo.Sistema)
        Return repository.GetSistemas(ativo, id)
    End Function

这是返回“Sistema”类型列表的函数

   Public Function GetSistemas(ativo As String, id As Integer) As List(Of DimSuporteModelo.Sistema) Implements ISistema.GetSistemas
        Dim objSistemaDataSource As New SistemaDataSource
        objSistemaDataSource.Contexto.ContextOptions.ProxyCreationEnabled = False
        If ativo = "True" Then
            ativo = True
        Else
            ativo = False
        End If
        Dim listaSistemas As List(Of DimSuporteModelo.Sistema) = objSistemaDataSource.SelecionaVariosPorExpressao(Function(x) x.sisAtivo = ativo AndAlso x.cliID = id And x.sisID = 4)
        Return listaSistemas
    End Function

不确定是什么导致错误..我是Web Api的新手,也许我忘了添加一些东西?

编辑:这是我得到的json文件作为响应,显然在序列化过程中发生了错误

{
$id: "1"
Message: "An error has occurred."
ExceptionMessage: "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'."
ExceptionType: "System.InvalidOperationException"
StackTrace: null
InnerException: {
$id: "2"
Message: "An error has occurred."
ExceptionMessage: "Error getting value from 'ServerVersion' on 'System.Data.EntityClient.EntityConnection'."
ExceptionType: "Newtonsoft.Json.JsonSerializationException"
}

如果需要,我可以包括整个内部异常(它很长),但我没有看到任何相关内容。

1 个答案:

答案 0 :(得分:0)

在查看了我的整个代码之后,我在'Sistema'部分类中发现了一个错误,我在其中创建了一些属性,我正在创建一个'SistemaDataSource'实例,即用数据库定义我的Context的类,在任何属性之外,所以它正在向服务返回的Sistema对象添加连接的实例。当JsonSerializer尝试序列化连接时,ServerVersion将为null,因为连接已关闭。

Partial Public Class Sistema
    Dim objSistemaDataSource as new SistemaDataSource <- The problem!!!
    Public Overridable ReadOnly Property RetornarNomeDoSistema As String
        Get
            Return Me.sisNome
        End Get
    End Property
End Class

希望这可以帮助遇到同样问题的人,保持代码清洁! :)