发送GET请求时WEB API无法正常工作

时间:2018-02-14 05:14:53

标签: asp.net-web-api server response socket-timeout-exception mysql.data

我创建了一个WEB-API。它在我的本地和我的服务器上运行良好。但是现在当我尝试发送请求时,它会给我以下错误。

{
"Message": "An error has occurred.",
"ExceptionMessage": "An error occurred while executing the command definition. See the inner exception for details.",
"ExceptionType": "System.Data.Entity.Core.EntityCommandExecutionException",
"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__DisplayClass7.<GetResults>b__6()\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__DisplayClass7.<GetResults>b__5()\r\n   at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.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.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()\r\n   at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()\r\n   at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)\r\n   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__1[TResult](IEnumerable`1 sequence)\r\n   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)\r\n   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)\r\n   at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)\r\n   at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source)\r\n   at ActualWebService.Controllers.MetersController.GetByMsn(String msn, DateTime dt) in E:\\Work\\NEW API\\ActualWebService\\ActualWebService\\Controllers\\MetersController.cs:line 57",
"InnerException": {
    "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.MySqlCommand.ExecuteReader(CommandBehavior behavior)\r\n   at MySql.Data.Entity.EFMySqlCommand.ExecuteDbDataReader(CommandBehavior behavior)\r\n   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)\r\n   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c)\r\n   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 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)",
    "InnerException": {
        "Message": "An error has occurred.",
        "ExceptionMessage": "Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.",
        "ExceptionType": "System.TimeoutException",
        "StackTrace": "   at MySql.Data.Common.MyNetworkStream.Read(Byte[] buffer, Int32 offset, Int32 count)\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.GetResult(Int32& affectedRow, Int64& insertedId)\r\n   at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)\r\n   at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)\r\n   at MySql.Data.MySqlClient.MySqlDataReader.NextResult()\r\n   at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)",
        "InnerException": {
            "Message": "An error has occurred.",
            "ExceptionMessage": "Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.",
            "ExceptionType": "System.IO.IOException",
            "StackTrace": "   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)\r\n   at MySql.Data.Common.MyNetworkStream.Read(Byte[] buffer, Int32 offset, Int32 count)",
            "InnerException": {
                "Message": "An error has occurred.",
                "ExceptionMessage": "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond",
                "ExceptionType": "System.Net.Sockets.SocketException",
                "StackTrace": "   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)\r\n   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)"
            }
        }
    }
}

WEB-API部署在iis服务器上。以下是我的web.config文件。

<add name="MDCEntities" connectionString="metadata=res://*/Models.MeterModel.csdl|res://*/Models.MeterModel.ssdl|res://*/Models.MeterModel.msl;provider=MySql.Data.MySqlClient;provider connection string=&quot;protocol=Socket;server=ip;port=port;user id=user;password=pass;persistsecurityinfo=True;database=kesc;sslmode=None;compress=False;allowuservariables=True;allowzerodatetime=False;Integrated Security=False;treattinyasboolean=False&quot;" providerName="System.Data.EntityClient" />

 <httpRuntime targetFramework="4.5" requestPathInvalidCharacters="&lt;,&gt;,&amp;,*,\,?" executionTimeout="1000" />

以下是我的控制器代码

 public class MetersController : ApiController
{

    public MDCEntities medEntitites = new MDCEntities();

    // GET: Meters by MSN    

    //[System.Web.Http.Route("api/meters/{msn:int}/{dt:DateTime}")]
    public HttpResponseMessage GetByMsn(string msn, DateTime dt)
    {          
        try
        {
            // var dateTime = dt.ToString();
            SqlConnection con = new SqlConnection("");

            //var before = dt.AddMinutes(-5);
            //var after = dt.AddMinutes(5);
            //var result = medEntitites.tj_xhqd
            //             .Where(m =>
            //             m.zdjh == msn &&
            //             m.sjsj >= before &&
            //             m.sjsj <= after).Select(m => new { MSN = m.zdjh, DateTime = m.sjsj, Signal_Strength = m.xhqd }).Distinct().ToList();

            var result = medEntitites.tj_xhqd.Where(m => m.zdjh == msn)
                                             .OrderByDescending(o => o.sjsj)
                                             .Select(s => s.sjsj)
                                             .FirstOrDefault();

            DateTime resulted = new DateTime();
            DateTime userSent = new DateTime();

            resulted = Convert.ToDateTime(result);
            userSent = Convert.ToDateTime(dt);


            double diff = Math.Abs((resulted - userSent).TotalMinutes);

            if (diff <=10)
            {
                return Request.CreateResponse(HttpStatusCode.OK, new { data = new { Response = "Yes"} });
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.OK, new { data = new { Response = "No" } });
            }

        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
        }
    }

}

错误发生在var result

Webapi.config

 config.Routes.MapHttpRoute(
       name: "GetByMsn",
       routeTemplate: "api/{controller}/{action}/{msn}/{dt}",
       defaults: null,
       constraints: new { msn = @"^[0-9]+$" , dt = @"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$" }
       );

以前,它工作正常。但我不知道为什么它没有给出答复。

任何帮助都将受到高度赞赏。

0 个答案:

没有答案