Newtonsoft's Json.Net is obviously capable of deserializing NaN, but I can't seem to coerce it to do it into a provided float field. I get an Unexpected character "N" exception.
In the following code:
using Newtonsoft.Json;
namespace TestNanDeserialize
{
public class Number
{
public float Float;
}
public class Empty
{
}
internal class Program
{
private const string testJson = "{float: NaN}";
private static void Main(string[] args)
{
Succeeds();
Fails();
}
private static void Succeeds()
{
var result = JsonConvert.DeserializeObject<Empty>(testJson);
}
private static void Fails()
{
var result = JsonConvert.DeserializeObject<Number>(testJson);
}
}
}
Succeeds() and Fails() generate two very different call stacks:
Succeeds()
Newtonsoft.Json.dll!Newtonsoft.Json.JsonTextReader.ParseNumberNaN() Line 2299 C#
Newtonsoft.Json.dll!Newtonsoft.Json.JsonTextReader.ParseValue() Line 1572 C#
Newtonsoft.Json.dll!Newtonsoft.Json.JsonTextReader.Read() Line 381 C#
Newtonsoft.Json.dll!Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(object newObject, Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty member, string id) Line 2331 C#
Newtonsoft.Json.dll!Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, object existingValue) Line 485 C#
Newtonsoft.Json.dll!Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, object existingValue) Line 291 C#
Newtonsoft.Json.dll!Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(Newtonsoft.Json.JsonReader reader, System.Type objectType, bool checkAdditionalContent) Line 167 C#
Newtonsoft.Json.dll!Newtonsoft.Json.JsonSerializer.DeserializeInternal(Newtonsoft.Json.JsonReader reader, System.Type objectType) Line 823 C#
Newtonsoft.Json.dll!Newtonsoft.Json.JsonSerializer.Deserialize(Newtonsoft.Json.JsonReader reader, System.Type objectType) Line 802 C#
Newtonsoft.Json.dll!Newtonsoft.Json.JsonConvert.DeserializeObject(string value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) Line 863 C#
Newtonsoft.Json.dll!Newtonsoft.Json.JsonConvert.DeserializeObject<TestNanDeserialize.Empty>(string value, Newtonsoft.Json.JsonSerializerSettings settings) Line 820 C#
Newtonsoft.Json.dll!Newtonsoft.Json.JsonConvert.DeserializeObject<TestNanDeserialize.Empty>(string value) Line 757 C#
TestNanDeserialize.exe!TestNanDeserialize.Program.Succeeds() Line 26 C#
TestNanDeserialize.exe!TestNanDeserialize.Program.Main(string[] args) Line 20 C#
Fails()
Newtonsoft.Json.dll!Newtonsoft.Json.JsonTextReader.ReadAsDouble() Line 948 C#
Newtonsoft.Json.dll!Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonContract contract, bool hasConverter) Line 2214 C#
Newtonsoft.Json.dll!Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(object newObject, Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty member, string id) Line 2359 C#
Newtonsoft.Json.dll!Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, object existingValue) Line 485 C#
Newtonsoft.Json.dll!Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, object existingValue) Line 291 C#
Newtonsoft.Json.dll!Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(Newtonsoft.Json.JsonReader reader, System.Type objectType, bool checkAdditionalContent) Line 167 C#
Newtonsoft.Json.dll!Newtonsoft.Json.JsonSerializer.DeserializeInternal(Newtonsoft.Json.JsonReader reader, System.Type objectType) Line 823 C#
Newtonsoft.Json.dll!Newtonsoft.Json.JsonSerializer.Deserialize(Newtonsoft.Json.JsonReader reader, System.Type objectType) Line 802 C#
Newtonsoft.Json.dll!Newtonsoft.Json.JsonConvert.DeserializeObject(string value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) Line 863 C#
Newtonsoft.Json.dll!Newtonsoft.Json.JsonConvert.DeserializeObject<TestNanDeserialize.Number>(string value, Newtonsoft.Json.JsonSerializerSettings settings) Line 820 C#
Newtonsoft.Json.dll!Newtonsoft.Json.JsonConvert.DeserializeObject<TestNanDeserialize.Number>(string value) Line 757 C#
TestNanDeserialize.exe!TestNanDeserialize.Program.Fails() Line 31 C#
TestNanDeserialize.exe!TestNanDeserialize.Program.Main(string[] args) Line 21 C#
You might think that should be enough for debug this, and perhaps it should, but it doesn't actually make obvious to me what forks were supposed to have occurred differently in all of these layers to make it work.
EDIT: Yes, I'm aware that unquoted NaN is not valid JSON. A stated feature of Json.Net is support for NaN. It obviously is capable of deserializing it, as the code above demonstrates. I'm not certain, however, that it can deserialize into a float field.
NOTE: I've opened a defect for this at: https://github.com/JamesNK/Newtonsoft.Json/issues/908
The cause of your difficulty is that your JSON is invalid -- specifically the symbol NaN needs to be quoted. I.e. the following JSON can be deserialized into your Number class:
{"float": "NaN"}
And the following cannot:
{float: NaN}
Note that there is a setting, FloatFormatHandling.Symbol, that allows NaN to be output without quotes, so it may be earlier versions of Json.NET were able to parse non-quoted NaN strings as float or double. But that seems not to be the case currently. See Serializing NaN results in non-JSON compliant text and also Json.NET 5.0 Release 1: Serializing NaN and Infinity Floating Point Values.
Update 2
I tried deserializing the unquoted JSON string {float: NaN} in various versions of Json.NET:
8.0.2 (current): fails.
7.0.1: succeeds.
3.5: succeeds.
So this may be a regression. You might want to report an issue.
Update
As pointed out by #shannon, there's an inconsistency in Json.NET's extensions to the JSON standard. JToken.Parse("NaN") returns a JValue of type Float, but JsonConvert.DeserializeObject<double>("NaN") throws an exception. It's possible to use this inconsistency to write a converter that handles non-quoted NaN strings:
public class FloatNanConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(float) || objectType == typeof(float?);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var value = JValue.Load(reader);
if (objectType == typeof(float?))
return (float?)value;
else
return (float)value;
}
public override bool CanWrite { get { false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Related
I am using Asp.Net Web Api Identity - Individual User Account. I am returning AspNetUser Table Data from Web API.
Note : This table is made my asp.net itself, not me. But, I changed its connection string to store it in a pre-exiting database in Sql, and now, returning table data causes Internal Server Error.
public AspNetUser Get(string id)
{
using (UserDBEntities entities = new UserDBEntities())
{
return entities.AspNetUsers.FirstOrDefault(u => u.UserName == id);
}
}
And class for AspNetUser table is default, as individual user account proposes.
If I do it like below, error still persist on normal run, but not while debugging, that is when I debug the code step-by-step, it works file, and returns correct data, but when I remove my breakpoints and execute OR press continue while debugging instead of going step wise to return statement, it runs into error.
AspNetUser data = entities.AspNetUsers.FirstOrDefault(u => u.UserName == id);
return data;
Unlike this scenario, Returning without storing data, runs into error in all cases (debugging or not).
But, I don't understand, why??
how come this can affect anyhow?
Network Error Response Body:=>
{"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 getting value from 'AspNetUserClaims' on 'System.Data.Entity.DynamicProxies.AspNetUser_4C1FDBB9E07016D6C527FBA4F5785F2C7FE37C77A86A5D1946B99CFFDE56DB7F'.","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":" at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, 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.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__22.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.get_Connection()\r\n at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)\r\n at System.Data.Entity.Core.Objects.ObjectQuery`1.Execute(MergeOption mergeOption)\r\n at System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(List`1 collection, MergeOption mergeOption)\r\n at System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(MergeOption mergeOption)\r\n at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()\r\n at System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)\r\n at System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass7`2.<GetInterceptorDelegate>b__1(TProxy proxy, TItem item)\r\n at System.Data.Entity.DynamicProxies.AspNetUser_4C1FDBB9E07016D6C527FBA4F5785F2C7FE37C77A86A5D1946B99CFFDE56DB7F.get_AspNetUserClaims()\r\n at GetAspNetUserClaims(Object )\r\n at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"}}}
I want to know the reason of this anomaly, not any solution, because it can be solved by returning a defined class, Like this =>
User user = new User();
AspNetUser data = entities.AspNetUsers.FirstOrDefault(u => u.UserName == id);
user.reg_username = data.UserName;
user.reg_email = data.Email;
return user;
I have created a simple custom JsonConverter - code below - to simply change the error message generated when an invalid date is passed.
This is being used in an ASP.Net MVC site and also ASP.Net Web API for Ajax calls.
I am posting a DTO (partial code below) via ajax. When i do this on my local environment everything functions as it should; when the date is invalid I receive a bad request along with the correct error message
When i publish this to a production server it's totally ignored and i receive the default ModelState list of errors.
I have verified my web.config and Newtonsoft versions; they're the same both locally and on the server.
Why would the converter be ignored on production?
Converter is:
public class CustomDateValidationConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (string.IsNullOrEmpty(reader.Value.ToString()))
return null;
DateTime d;
DateTime.TryParse(reader.Value.ToString(), out d);
if (d == null || d == DateTime.MinValue)
throw new Exception(string.Format("{0} is invalid", reader.Path.AddSpacesBeforeUppercase(true)));
return d;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, DateTime.Parse(value as string));
}
}
I am using it in my DTO as:
.....
[JsonConverter(typeof(CustomDateValidationConverter))]
[DateLessThanOrEqual("CreateDateTo", "Create Date From must be on or before Create Date To")]
public DateTime? CreateDateFrom { get; set; }
.....
Check Your Production Server Date format, It may differ from your Development environment. so It may accept you input date format as valid
I have developed a project usein Asp.Net Web API, followint the Entity Framework code-first approach.
I have tested it in local machine with a local DB in Visual Studio 2013 and it works correctly.
The problem comes when I replace the connection string and deploy the DB to Azure. I'm able to perform some queries, but not other.
For example if I enter in the browser http://my-site/api/users/1 I get the expected result. However the query http://my-site/api/users/ return me an error related to Json serialization:
{ "$id" : "1",
"ExceptionMessage" : "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
"ExceptionType" : "System.InvalidOperationException",
"InnerException" : { "$id" : "2",
"ExceptionMessage" : "Error getting value from 'Devices' on 'System.Data.Entity.DynamicProxies.User_50420314CCDC05AAF3288A574C1CBB8436C09BAEF7539C2795445FCBA161AC99'.",
"ExceptionType" : "Newtonsoft.Json.JsonSerializationException",
"InnerException" : { "$id" : "3",
"ExceptionMessage" : "An error occurred while executing the command definition. See the inner exception for details.",
"ExceptionType" : "System.Data.Entity.Core.EntityCommandExecutionException",
"InnerException" : { "$id" : "4",
"ExceptionMessage" : "There is already an open DataReader associated with this Command which must be closed first.",
"ExceptionType" : "System.InvalidOperationException",
"Message" : "An error has occurred.",
"StackTrace" : " at System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command)\r\n at System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command)\r\n at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)\r\n at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)\r\n at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)\r\n at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)\r\n at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)\r\n at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)\r\n at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<>c__DisplayClassb.<Reader>b__8()\r\n at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`1 executed)\r\n at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)\r\n at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)\r\n at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)\r\n at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)"
},
"Message" : "An error has occurred.",
"StackTrace" : " at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)\r\n at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)\r\n at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__a()\r\n at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)\r\n at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__9()\r\n at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)\r\n at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)\r\n at System.Data.Entity.Core.Objects.ObjectQuery`1.Execute(MergeOption mergeOption)\r\n at System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(List`1 collection, MergeOption mergeOption)\r\n at System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(MergeOption mergeOption)\r\n at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.Load()\r\n at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()\r\n at System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)\r\n at System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass7`2.<GetInterceptorDelegate>b__1(TProxy proxy, TItem item)\r\n at System.Data.Entity.DynamicProxies.User_50420314CCDC05AAF3288A574C1CBB8436C09BAEF7539C2795445FCBA161AC99.get_Devices()\r\n at GetDevices(Object )\r\n at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"
},
"Message" : "An error has occurred.",
"StackTrace" : " at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\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.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, 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 Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value)\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.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__19.MoveNext()"
},
"Message" : "An error has occurred.",
"StackTrace" : null
}
This problem is really annoying me, because as I mentioned, with the local DB works fine. The databases generated locally and in Azure seems equal. So, I can't guess where the problem could be.
The answer is what the error message tells you. It cannot serialize Entity Framework Proxy to JSON. You should map to POCO classes and return them:
//poco
public class PersonPoco
{
public string FirstName {get;set;}
public string LastName {get;set;}
}
//controller
public IEnumerable<PersonPoco> Get()
{
var person = _personRepository.FindAll();
person.Select(x=> new PersonPoco() {
FirstName = x.f_name,
LastName = x.l_name
}).ToList();
}
you can use AutoMapper to do this conversion, you can create Extension methods to do this conversion. Anyway, it's just a sample.
Adding .ToArray() to the result I was returning from my GetAll() method solved the problem:
public IEnumerable<TEntity> GetAll()
{
return _dbContext.Set<TEntity>().ToArray();
}
But, I'm still wondering why it was working with the local DB and not with the DB deployed to Azure.
Adding MultipleActiveResultSets=True also solved my issue. But since I don't really know what does enabling that feature entail, I opted for the first option.
I have simple project, where I'm using signalR, When page loads, signalR scripts are loaded succefully, however right after that, call to
http://localhost:24634/signalr/signalr/connect?transport=foreverFrame&connectionId=dca2db9c-b16a-4b96-96dc-9a6b187b6d9e&connectionData=[{"name":"notifier"}]&tid=5&frameId=1
returns 500 Internal Server Error, I checked this request in fiddler, error message says
Unexpected end when deserializing object.
Here's my Hub Definitin
[HubName("notifier")]
public class PublishingNotifier: Hub
{
[HubMethodName("send")]
public void SendMessage(string message)
{
Clients.getNotification(message);
}
}
and here's my client code
$(function () {
var publishingNotifier = $.connection.notifier;
publishingNotifier.getNotification = function (message) {
// do something
};
$('input[type=submit][id*=cmsB_ChangeStatusToPublishedTop]').on('click', function (e) {
// do something else
});
$.connection.hub.start();
});
Any ideas what can be cause of this error ?
EDIT
Here is Stack Trace information
[JsonSerializationException: Unexpected end when deserializing object.
Line 1, position 2.]
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CheckedRead(JsonReader
reader) +75
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader
reader, Type objectType, JsonContract contract, JsonProperty member,
Object existingValue) +48
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader
reader, Type objectType, JsonContract contract, JsonProperty member,
Object existingValue) +86
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateList(IWrappedCollection
wrappedList, JsonReader reader, String reference, JsonArrayContract
contract) +635
Newtonsoft.Json.Serialization.<>c_DisplayClass1.<CreateAndPopulateList>b_0(IList
l, Boolean isTemporaryListReference) +124
Newtonsoft.Json.Utilities.CollectionUtils.CreateAndPopulateList(Type
listType, Action2 populateList) +546
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateAndPopulateList(JsonReader
reader, String reference, JsonArrayContract contract) +101
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList(JsonReader
reader, Type objectType, JsonContract contract, JsonProperty member,
Object existingValue, String reference) +62
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader
reader, Type objectType, JsonContract contract, JsonProperty member,
Object existingValue) +113
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueNonProperty(JsonReader
reader, Type objectType, JsonContract contract, JsonConverter
converter) +118
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader
reader, Type objectType) +125
Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader,
Type objectType) +311
Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type,
JsonSerializerSettings settings) +107
Newtonsoft.Json.JsonConvert.DeserializeObject(String value,
JsonSerializerSettings settings) +66
SignalR.JsonNetSerializer.Parse(String json) +57
SignalR.Hubs.HubDispatcher.CreateConnection(String connectionId,
IEnumerable1 groups, IRequest request) +140
SignalR.PersistentConnection.ProcessRequestAsync(HostContext context)
+227 SignalR.Hubs.HubDispatcher.ProcessRequestAsync(HostContext context) +120
SignalR.Hosting.AspNet.AspNetHandler.ProcessRequestAsync(HttpContextBase
context) +463
SignalR.Hosting.AspNet.HttpTaskAsyncHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext
context, AsyncCallback cb, Object extraData) +68
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+301 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
EDIT2:
One more note - from the page that runs without any errors, requested url looks like this
localhost:24634/signalr/signalr/connect?transport=foreverFrame&connectionId=98e6d5b3-b164-4013-92c2-418aa6254f9e&connectionData=%5B%7B%22name%22%3A%22notifier%22%7D%5D&tid=7&frameId=1
and the failing request url looks like this
localhost:24634/signalr/signalr/connect?transport=foreverFrame&connectionId=9b398750-99d6-4188-88b5-b41ad9eb82d5&connectionData=[{"name":"notifier"}]&tid=1&frameId=1
As you may notice, the ways connectionData query string parameter is defined in urls are different, in particular, for the first url, connectionData has been url encoded the query string value, and the second query string parameter has been html encoded. I've looked into request headers, failing request Content-Type is text/html, and the second request's Content-Type: application/json.
EDIT 3:
I've found where connectionData get's parsed, in jquery.signalR-0.5.3.js file, here's code that actually encodes connectionData value
if (connection.data) {
qs += "&connectionData=" + window.escape(connection.data);
}
as you can see, window.escape() is responsible for encoding connectionData, but, if I debug this code, I can see that window.escape(connection.data) indeed html encodes connection.data instead of url encoding. But this is happening only on one page, on anothers, it works as expected.
To sum up, the problem turned out to be that window.escape was overridden by a third party JS library. This caused window.escape to behave differently than "normal" causing SignalR to fail as a side-effect.
So basically - when these "weird" issues occur - check if you have included libraries that "interfere" and make sure to use proper namespacing ( e.g. using the module pattern ) to avoid this issue.
BUG
I do not know if this could help, but I had the error "unexpected end when deserializing object message c #", when I was trying to deserialize my json.
It happened to me sometimes, sometimes not. I do not know what it depends on.
My json was like that:
https://api.myjson.com/bins/l83m8
Debugging the Xamarin App on visual studio 2019 gives me the following:
var content = await _client.GetStringAsync(Connection.URL);
invitaciones = JsonConvert.DeserializeObject<RootObject>(content);
The variable "content" sometimes gives me https://textsaver.flap.tv/lists/2lss and sometimes gives me https://textsaver.flap.tv/lists/2lsu.
If you look very carefully, you are gonna release that both are different, only because, the first one is missing a } just in the end.
If you deserialize both with https://www.unserialize.me/ tool, and then validate the result on https://jsonformatter.curiousconcept.com/ (default options), you are gonna see that the first one isn't valid, and the second is valid.
Solution:
Add a validation: if the string content (json) don't ends with }, put a } on the end.I know it's pretty silly, but solves my problem.
var content = await _client.GetStringAsync(Connection.URL);
if (!content.EndsWith("}"))
content = content + "}";
invitaciones = JsonConvert.DeserializeObject<RootObject>(content);
Packages: Newtonsoft.Json 12.0.2, Xamarin.Forms 3.6.0.344457 .
In ASP.NET MVC 4.0 WebAPI (beta version), I am returning an object that is serialised to JSON that is larger than 65kb. As you can see from the stack trace below, the framework is throwing an exception because this exceeds some internal limit.
System.Net.Http.HttpRequestException: Cannot write more bytes to the buffer than the configured maximum buffer size: 65536.
at System.Net.Http.HttpContent.LimitMemoryStream.CheckSize(Int32 countToAdd)
at System.Net.Http.HttpContent.LimitMemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
at System.IO.StreamWriter.Write(Char value)
at Newtonsoft.Json.JsonWriter.AutoComplete(JsonToken tokenBeingWritten) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\JsonWriter.cs:line 634
at Newtonsoft.Json.JsonTextWriter.WritePropertyName(String name) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\JsonTextWriter.cs:line 204
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.WriteMemberInfoProperty(JsonWriter writer, Object memberValue, JsonProperty property, JsonContract contract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 209
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContract collectionValueContract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 336
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.WriteMemberInfoProperty(JsonWriter writer, Object memberValue, JsonProperty property, JsonContract contract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 209
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContract collectionValueContract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 336
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContract collectionValueContract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 445
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.WriteMemberInfoProperty(JsonWriter writer, Object memberValue, JsonProperty property, JsonContract contract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 209
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContract collectionValueContract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 336
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.WriteMemberInfoProperty(JsonWriter writer, Object memberValue, JsonProperty property, JsonContract contract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 209
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContract collectionValueContract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 336
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContract collectionValueContract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 445
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 59
at xxx.Api.JsonNetFormatter.<>c__DisplayClass5.<OnWriteToStreamAsync>b__4() in c:\xxx\xxx\xxx.Api\JsonNetFormatter.cs:line 79
at System.Threading.Tasks.Task.Execute()
I can't find any way to change this default. Can anyone help?
thanks
According to the System.Net.Http.dll released with the nightly source code builds, value of the max buffer size is defined in HttpContent as :
internal const long MaxBufferSize = 0x7fffffffL; // 2147483647
So if you switch to the new version (rather than the beta installer) the problem should go away.
I suggest to switch anyway regardless of this problem as there are quite a few breaking changes and whatever you are building now is guaranteed not to work with the final release.