我在web api中有一个叫做"投票"的控制器,这是一个从主体获取一些参数的帖子请求,如果成功,它应该返回选民的id,或者返回&# 34;已投票"如果他之前投了票。对于第二种情况,我说得对。但当用户投票成功时,我收到此错误
{
"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
任何帮助将不胜感激, 提前谢谢
答案 0 :(得分:1)
内部异常看起来与实体框架有关。 EF中的“上下文已被处理......”错误通常与deferred execution相关。您确定您的USING范围内的所有内容都是立即执行的吗?我特别关注entities.SP_Voting_Insert()方法。我只能推断它的作用,但是你可能需要确保它立即执行,而不是在处理对象上下文之后。
(会发表评论,但唉......我还没有这个特权。)