WebAPI不发送数据

时间:2016-11-16 21:47:50

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

我正在使用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 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>

有人可以给我一些指示,继续寻找。

由于 卡洛斯

2 个答案:

答案 0 :(得分:2)

你正在返回private ArrayList<ImageView> makeImageViewArr(File imagesDir) { File[] strImageList = imagesDir.listFiles(); myMouseHandler mouseHandler = new myMouseHandler(); //instantiate imageview arraylist arrImageList = new ArrayList<ImageView>(); //get files from folder & start at 1 to ignore ds.Store for( int count = 1; count < strImageList.length; count++ ) { ImageView imgView = new ImageView( strImageList[ count ].toURI().toString() ); imgView.setOnMouseClicked( mouseHandler ); imgView.setFitHeight(500); imgView.setFitWidth(500); imgView.setPreserveRation(true); arrImageList.add( imgView ); } return arrImageList; } 对象,除非你在收到它之后以某种方式查询它,它不会给你数据。尝试先查询它,例如:

IQueryable

答案 1 :(得分:0)

这是一个糟糕的DateTime Field !!!我测试了另一个没有DateTime值的实体集并且表现更好,现在我只需要弄清楚如何处理这个错误:

{“消息”:“发生错误。”,“ExceptionMessage”:“SystemContent 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 \ n在System.Data.Entity.Internal.InternalContext 。&lt;&gt; 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 \ n在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 \ n at System.Data.Entity.Internal.Linq.InternalSet 1.GetEnumerator()\r\n at System.Data.Entity.Infrastructure.DbQuery 1.System.Collections.IEnumerable.GetEnumerator()\ r \ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer,IEnumerable values,JsonArrayContract)合同,JsonProperty成员,JsonContainerContract collectionContract,JsonProperty containerProperty)\ r \ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer,Object value,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\ r \ n在Newtonsoft .Json.Serialization.JsonSerializerInternalWriter.Serialize(JSON Writer jsonWriter,Object value,Type objectType)\ r \ n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter,Object value,Type objectType)\ r \ n在System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type) ,System.Net.Http中的System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(类型类型,对象值,流writeStream,编码effectiveEncoding)\ r \ n中的,对象值,流writeStream,编码effectiveEncoding)\ r \ n。 Format.BaseJsonMediaTypeFormatter.WriteToStream(Type type,Object value,Stream writeStream,HttpContent content)\ r \ n在System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type,Object value,Stream writeStream,HttpContent content,TransportContext transportContext, CancellationToken cancellationToken)\ r \ n ---从抛出异常的上一个位置开始的堆栈跟踪结束---在System.Runtime上的System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)\ r \ n中的\ r \ n \ n \ n \ n .Compil在System.Web.Http.WebHost.HttpControllerHandler.d__1b.MoveNext()“}}

中的erServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)\ r \ n

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