WebAPI 不发送数据

本文关键字:数据 WebAPI | 更新日期: 2023-09-27 18:18:11

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

我使用 DB (SQL SERVER( 连接字符串生成 ADO.NET 实体,因此我与数据库建立了连接。

最简单的 WebAPI 函数:

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

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

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

我的网络配置:

<?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>

有人可以给我一些指示继续寻找的地方吗?

谢谢卡洛斯

WebAPI 不发送数据

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

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

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

{"消息":">

发生错误。","异常消息":"'对象内容1' 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.CreateDatabaseIfNotExists 1.InitializeDatabase(TContext context(''r' at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf 1.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.RetryAction 1.PerformAction(TInput input(''r' at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action 1 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.InternalSet 1.Initialize((''r' at System.Data.Entity.Internal.Linq.InternalSet 1.GetEnumerator()'r'n at System.Data.Entity.Infrastructure.DbQuery 1.System.Collections.IEnumerable.GetEnumerator((''r' atNewtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty(''r' at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty(''r'at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType(''r' at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType(''r' at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding(''r' at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Objectvalue, Stream writeStream, Encoding effectiveEncoding(''r' at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content(''r' at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancelToken cancelToken(''r'--- 从异常为 的上一个位置开始的堆栈跟踪结束---在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task(''r' at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task(''r' 在 System.Web.Http.WebHost.HttpControllerHandler.d__1b 处抛出。MoveNext(("}}

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