【问题标题】:.net web api does not return in json format.net web api 不以 json 格式返回
【发布时间】:2018-03-03 16:11:10
【问题描述】:

我在 web api 中有一个名为“vote”的控制器,这是一个 post 请求,它从 body 中获取一些参数,如果成功,它应该返回选民的 id,如果他有,则返回“already voted”之前投票。对于第二种情况,我是对的。但是当用户投票成功时,我会收到此错误

   {
"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": {
    "message": "An error has occurred.",
    "exceptionMessage": "Error while copying content to a stream.",
    "exceptionType": "System.Net.Http.HttpRequestException",
    "stackTrace": "   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()",
    "innerException": {
        "message": "An error has occurred.",
        "exceptionMessage": "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.",
        "exceptionType": "System.ObjectDisposedException",
        "stackTrace": "   at System.Data.Entity.Core.Objects.ObjectContext.ReleaseConnection()\r\n   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1.Finally()\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n   at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n   at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n   at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n   at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)"
    }
}
}

这是我的 webapi 配置

Public Class CustomJsonFormatter
    Inherits JsonMediaTypeFormatter

    Public Sub New()
        Me.SupportedMediaTypes.Add(New System.Net.Http.Headers.MediaTypeHeaderValue("text/html"))
    End Sub

    Public Overrides Sub SetDefaultContentHeaders(ByVal type As Type, ByVal headers As HttpContentHeaders, ByVal mediaType As MediaTypeHeaderValue)
        MyBase.SetDefaultContentHeaders(type, headers, mediaType)
        headers.ContentType = New MediaTypeHeaderValue("application/json")
    End Sub
End Class

Module WebApiConfig

    Sub Register(ByVal config As HttpConfiguration)
        config.SuppressDefaultHostAuthentication()
        config.Filters.Add(New HostAuthenticationFilter(OAuthDefaults.AuthenticationType))
        config.MapHttpAttributeRoutes()



        config.Routes.MapHttpRoute(name:="DefaultApi", routeTemplate:="api/{controller}/{id}", defaults:=New With {Key .id = RouteParameter.[Optional]})

        config.Formatters.Remove(config.Formatters.XmlFormatter)
        config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented
        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = New Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
    End Sub
End Module

End Namespace

这是控制器

 Namespace Controllers
Public Class VoteController
    Inherits ApiController






    Function Post(<FromBody> ByVal user As Voting) As HttpResponseMessage

        Try
            Using entities As ElectionsEntities = New ElectionsEntities()
                Dim entity = entities.Votings.FirstOrDefault(Function(e) e.Elector_FK_ID = user.Elector_FK_ID)
                If entity Is Nothing Then
                    Dim message = Request.CreateResponse(HttpStatusCode.Created, entities.SP_Voting_Insert(user.Elector_FK_ID, user.City_FK_ID, user.Voting_Center_FK_ID, user.class_FK_ID))
                    message.Headers.Location = New Uri(Request.RequestUri, user.Elector_FK_ID.ToString())
                    Return message
                Else
                    Dim message = Request.CreateResponse(HttpStatusCode.BadRequest, "هذا الشخص قام بالتصويت")
                    Return message
                End If
            End Using
        Catch e As Exception
            Return Request.CreateErrorResponse(HttpStatusCode.BadRequest, e)
        End Try
    End Function

End Class
 End Namespace 

这里是插入的SP

 @Elector_FK_ID bigint,
@City_FK_ID bigint,
@Voting_Center_FK_ID bigint,
@class_FK_ID as bigint
 AS
 BEGIN

SET NOCOUNT ON;


insert into [Elections].[dbo].[Voting]
(
    [Elector_FK_ID],[VoteDate],[City_FK_ID],[Voting_Center_FK_ID],[class_FK_ID]
)
values
(
    @Elector_FK_ID,getdate(),@City_FK_ID,@Voting_Center_FK_ID,@class_FK_ID
)
select @@IDENTITY

任何帮助将不胜感激, 在此先感谢

【问题讨论】:

    标签: .net json vb.net entity-framework asp.net-web-api


    【解决方案1】:

    内部异常看起来与实体框架有关。 EF 中的“上下文已被处理...”错误通常与deferred execution 相关。您确定 USING 范围内的所有内容都会立即执行吗?我特别关注entities.SP_Voting_Insert() 方法。我只能推断它做了什么,但您可能需要确保它立即执行,而不是在对象上下文被释放之后。

    (本来可以作为评论发布的,但是唉……我还没有这个特权。)

    【讨论】:

    • SP 工作正常,顺便说一下将用户添加到数据库,但它提示该错误,但我需要返回没有任何错误的响应
    • 嗯...用户创建方法 (SP_Voting_Insert) 是否包含任何可能处置对象上下文的代码?
    • 我更新了问题,我添加了我使用的SP,看看它
    • 也许是 SELECT @@IDENTITY 查询直到对象上下文被释放后才被执行。你能用断点调试吗?我会尝试将 SP_Voting_Insert() 的结果存储在一个变量中并检查它,或者您可以尝试调用 SP_Voting_Insert().ToString() 或类似的方法来强制执行。对于含糊的建议,我很抱歉——我有 EF 的经验,但没有 VB.NET。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2013-09-21
    • 1970-01-01
    • 2017-03-10
    • 2021-12-20
    相关资源
    最近更新 更多