2016-11-16 78 views
2

我正在開發使用Visual Studio 2015嘗試公開數據庫的最簡單的WebAPI。WebAPI不發送數據

我使用DB(SQL SERVER)連接字符串生成我的ADO.NET實體,所以我與數據庫連接。

最簡單的WebAPI功能:

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

不行的,我知道有連接與VISAUL工作室我的數據庫,但是當我運行SQL Server Profiler中我沒有看到查詢到DB從的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> 

有人請給我幾個指針,在哪裏繼續尋找。

感謝 卡洛斯

+0

什麼呢API返回 –

+0

的的WebAPI說,它與連接:? 公共BOOL TestConnection() { 使用(VAR DB =新deletemeWebAPIContext()) { 的DbConnection conn = db.Database.Connection; 嘗試 { conn.Open(); return tr UE; } catch { return false; } } } –

+0

它返回「[]」 –

回答

2

您傳回IQueryable對象,除非你以某種方式收到後查詢它,它不會給你的數據。嘗試先查詢它,例如:

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

這是darn DateTime Field !!!我測試了另一個沒有DateTime值的實體集,它表現更好,現在我只需要弄清楚如何處理這個錯誤:

{「Message」:「發生錯誤」,「ExceptionMessage」:「 'ObjectContent 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。<> 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輸入)\ 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在Newtonsoft.Json.Serialization上System.Data.Entity.Internal.Linq.InternalSet 1.GetEnumerator()\r\n at System.Data.Entity.Infrastructure.DbQuery 1.System.Collections.IEnumerable.GetEnumerator()\ r \ n。 JsonSerializerInternalWriter.SerializeList(JsonWriter作家,IEnumerable值,JsonArrayContract合同,JsonProperty成員,JsonContainerContract co在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter中的\ r \ n \ r \ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer,Object value,JsonContract valueContract,JsonProperty成員,JsonContainerContract containerContract,JsonProperty containerProperty) .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在System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type,Object value,Stream writeStream,Encoding effectiveEncoding)\ r \ n在System.Net .Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type,Object value,Stream writeStream,HttpContent content)\ r \ n在System.Net.Http.Formatting.BaseJso nMediaTypeFormatter.WriteToStreamAsync(Type type,Object value,Stream writeStream,HttpContent content,TransportContext transportContext,CancellationToken cancellationToken)\ r \ n ---在前一個拋出異常的位置結束堆棧跟蹤--- \ r \ n在System中。 Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任務任務)\ r \ n在System.Web.Http.WebHost.HttpControllerHandler.d__1b上System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任務任務)\ r \ n。我的密鑰是一個名爲'index'的字段,我必須在ADO.NET生成的類上添加[Key]註釋,我不知道我的[Key]標籤是否生成了驗證錯誤。 「環境已經改變,因爲數據庫創建」