【问题标题】:WebAPI not sending dataWebAPI不发送数据
【发布时间】:2016-11-16 21:47:49
【问题描述】:

我正在使用 Visual Studio 2015 开发最简单的 WebAPI,试图公开数据库。

我使用 DB (SQL SERVER) 连接字符串生成我的 ADO.NET 实体,因此我与 DB 有连接。

最简单的WebAPI函数:

// GET: api/avl_users
public IQueryable<avl_user> Getavl_users()
{
    return db.avl_users;
}

不起作用,我知道 Visaul Studio 与我的数据库有连接,但是当我运行我的 SQL Server Profiler 时,我看不到从 WebAPI 对数据库的查询

我测试我的 API 的方式是使用浏览器: http://localhost:53277/api/avl_users

我的 Web.config:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301879
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-deletemeWebAPI-20161116123948.mdf;Initial Catalog=aspnet-deletemeWebAPI-20161116123948;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="avlEntities" connectionString="metadata=res://*/Models.AvlModel.csdl|res://*/Models.AvlModel.ssdl|res://*/Models.AvlModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\SQLEXPRESS;initial catalog=avl;persist security info=True;user id=xxxxx;password=yyyyyy;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    <add name="deletemeWebAPIContext" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=deletemeWebAPIContext-20161116125552; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|deletemeWebAPIContext-20161116125552.mdf" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings></appSettings>
  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>

有人可以指点我在哪里继续寻找。

谢谢 卡洛斯

【问题讨论】:

  • api 返回什么?
  • WebAPI 说它连接到: public bool TestConnection() { using (var db = new deletemeWebAPIContext()) { DbConnection conn = db.Database.Connection;试试 { conn.Open();返回真; } 捕捉 { 返回错误; } } }
  • 它返回“[]”

标签: c# sql-server asp.net-web-api ado.net


【解决方案1】:

您返回的是 IQueryable 对象,除非您在收到它后以某种方式查询它,否则它不会给您数据。尝试先查询它,例如:

public List<avl_user> Getavl_users()
{
    return db.avl_users.ToList();
}

【讨论】:

    【解决方案2】:

    这是该死的日期时间字段!!!我测试了另一个没有 DateTime 值的实体集,它的性能更好,现在我只需要弄清楚如何处理这个错误:

    {"Message":"发生错误。","ExceptionMessage":"System.Data.Entity.Internal.InternalContext 处的 'ObjectContent1' type failed to serialize the response body for content type 'text/html; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"The model backing the 'deletemeWebAPIContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).","ExceptionType":"System.InvalidOperationException","StackTrace":" at System.Data.Entity.CreateDatabaseIfNotExists1.InitializeDatabase(TContext context)\r\n。c__DisplayClassf1.b__e()\r\n at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)\r\n at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()\r\n at System.Data.Entity.Internal.LazyInternalContext.b__4(InternalContext c)\r\n at System.Data.Entity.Internal.RetryAction1.PerformAction(TInput 输入)\r\n 在 System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1 action)\r\n at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()\r\n at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)\r\n at System.Data.Entity.Internal.Linq.InternalSet1.Initialize()\r\n 在 System.Data.Entity.Internal .Linq.InternalSet1.GetEnumerator()\r\n at System.Data.Entity.Infrastructure.DbQuery1.System.Collections.IEnumerable.GetEnumerator()\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty )\r\n 在 Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter 编写器、对象值、JsonContract valueContract、JsonProperty 成员、JsonContainerContract containerContract、JsonProperty containerProperty)\r\n 在 Newtonsoft.Json.Serialization.JsonSerializerInternalWri ter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n 在 Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n 在 System.Net.Http.Formatting.BaseJsonMediaTypeFormatter。 WriteToStream(类型类型,对象值,流 writeStream,编码有效编码)\r\n 在 System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(类型类型,对象值,流 writeStream,编码有效编码)\r\n 在系统。 Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(类型类型,对象值,流 writeStream,HttpContent 内容)\r\n 在 System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(类型类型,对象值,流 writeStream,HttpContent 内容, TransportContext transportContext, CancellationToken cancelToken)\r\n--- 从先前引发异常的位置结束堆栈跟踪 ---\r\n 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)\r\n在系统tem.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)\r\n 在 System.Web.Http.WebHost.HttpControllerHandler.d__1b.MoveNext()"}}

    我的键是一个名为“索引”的字段,我必须在 ADO.NET 生成的类上添加 [Key] 注释,我想知道我的 [Key] 标签是否生成了验证错误。 “自数据库创建以来,上下文发生了变化”。

    【讨论】:

      猜你喜欢
      • 2017-11-19
      • 1970-01-01
      • 2020-07-08
      • 2015-08-27
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      • 1970-01-01
      • 2016-10-07
      相关资源
      最近更新 更多