0

Below is my web-api.

public HttpResponseMessage GetMeterPing(DateTime start, DateTime end)
{
    try
    {
        var startDateTime = start;
        var endDateTime = end;

        var result = medEntitites.tj_xhqd.Where(m => m.sjsj >= startDateTime && m.sjsj <= endDateTime)
                                         .OrderByDescending(o => o.sjsj)
                                         .Select(s => new { s.zdjh, s.sjsj, s.xhqd });
                                         .Distinct();
                                         
        return Request.CreateResponse(HttpStatusCode.OK, new { data = result });
    }
    catch (Exception ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
    }
}

WEB-API UR:L http://localhost:14909/api/meters/GetMeterPing/2018-04-27T00:00:00/2018-04-28T23:59:59

When I run the above URL I am getting exceptions

{
"$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": "An error occurred while reading from the store provider's data reader. See the inner exception for details.",
    "ExceptionType": "System.Data.Entity.Core.EntityCommandExecutionException",
    "StackTrace": "   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1.HandleReaderException(Exception e)\r\n   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1.StoreRead()\r\n   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()\r\n   at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()\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.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__1b.MoveNext()",
    "InnerException": {
        "$id": "3",
        "Message": "An error has occurred.",
        "ExceptionMessage": "Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.",
        "ExceptionType": "MySql.Data.MySqlClient.MySqlException",
        "StackTrace": "   at MySql.Data.MySqlClient.ExceptionInterceptor.Throw(Exception exception)\r\n   at MySql.Data.MySqlClient.MySqlConnection.Throw(Exception ex)\r\n   at MySql.Data.MySqlClient.MySqlConnection.HandleTimeoutOrThreadAbort(Exception ex)\r\n   at MySql.Data.MySqlClient.MySqlDataReader.Read()\r\n   at MySql.Data.Entity.EFMySqlDataReader.Read()\r\n   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1.StoreRead()",
        "InnerException": {
            "$id": "4",
            "Message": "An error has occurred.",
            "ExceptionMessage": "Timeout in IO operation",
            "ExceptionType": "System.TimeoutException",
            "StackTrace": "   at MySql.Data.MySqlClient.TimedStream.StopTimer()\r\n   at MySql.Data.MySqlClient.TimedStream.Read(Byte[] buffer, Int32 offset, Int32 count)\r\n   at System.IO.BufferedStream.Read(Byte[] array, Int32 offset, Int32 count)\r\n   at MySql.Data.MySqlClient.MySqlStream.ReadFully(Stream stream, Byte[] buffer, Int32 offset, Int32 count)\r\n   at MySql.Data.MySqlClient.MySqlStream.LoadPacket()\r\n   at MySql.Data.MySqlClient.MySqlStream.ReadPacket()\r\n   at MySql.Data.MySqlClient.NativeDriver.FetchDataRow(Int32 statementId, Int32 columns)\r\n   at MySql.Data.MySqlClient.Driver.FetchDataRow(Int32 statementId, Int32 columns)\r\n   at MySql.Data.MySqlClient.ResultSet.GetNextRow()\r\n   at MySql.Data.MySqlClient.ResultSet.NextRow(CommandBehavior behavior)\r\n   at MySql.Data.MySqlClient.MySqlDataReader.Read()"
        }
    }
}
}

WebApiConfig

var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);

Application_Start()

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        GlobalConfiguration.Configuration.Formatters
            .Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

I have also looked into these solutions 1, 2 But it still gives me exceptions.

Also, I have tried with .ToList() but unable to get desired results.

Note: I am using MySQL Database

Update 1:

 var result = medEntitites.tj_xhqd.Where(m => m.sjsj >= startDateTime && m.sjsj <= endDateTime)
                                             .OrderByDescending(o => o.sjsj)
                                             .Select(s => new { s.zdjh, s.sjsj, s.xhqd })
                                             .Distinct()
                                             .FirstOrDefault();    

By using FirsOrDefault() I am getting a single row returned

{
"data": {
    "zdjh": "002999001089",
    "sjsj": "2018-04-27T00:00:00",
    "xhqd": "19"
}
}

But I want API to return all the records between the date time given

How can I get rid of these exceptions?

Any help would be highly appreciated.

Community
  • 1
  • 1
Moeez
  • 494
  • 9
  • 55
  • 147
  • Is your database up and running? And is the connection string correct? Is the query executing before SQL timeout? – danish May 02 '18 at 05:05
  • Yes, the database is up and running. The connection string is correct and if I try to run the same query directly in DB then it gives me results quickly. – Moeez May 02 '18 at 05:07
  • Use `.ToList()` after `Distinct()`. – Chetan May 02 '18 at 05:23
  • @ChetanRanpariya already used it gives me `An error occurred while reading from the store provider's data reader. See the inner exception for details.` – Moeez May 02 '18 at 05:25
  • This is linked with communication between the API and the database. Try debugging that part. I see you are using EF, spin up a quick ADO.Net code for connection and same query execution to see where the problem is. Also check if database allows remote connections. – danish May 02 '18 at 05:27
  • @danish it does allow a remote connect as I have another `GET` function which is working fine – Moeez May 02 '18 at 05:29
  • 1
    Looks like the query is taking too long to execute and times out at the code level. That's why you are seeing this error. Try to run the sql version of this query directly against the database in SSMS and see if it gives you the result. Also Try removing Distinct(). – Chetan May 02 '18 at 05:30
  • @ChetanRanpariya I have tried to run the `MySQL` version of the query and it does gives me result – Moeez May 02 '18 at 05:38
  • @ChetanRanpariya you are right, LINQ is taking time. So I have tried to reduce the time from 48 hours span to 12 hours span and it did work – Moeez May 02 '18 at 06:07

0 Answers0