【发布时间】: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