2016-05-19 34 views
0

可能な解決策をすべて実行しようとしましたが、正しい答えが得られませんでした。以下は私のコードです:Web APIエラー: 'ObjectContent`1'タイプのシリアル化に失敗しました

WebApiConfig.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web.Http; 
using System.Net.Http.Headers; 

namespace WebAPI 
{ 
    public static class WebApiConfig 
    { 
     public static void Register(HttpConfiguration config) 
     { 
      // Web API configuration and services 

      // Web API routes 
      config.MapHttpAttributeRoutes(); 
      //test 
      var json = config.Formatters.JsonFormatter; 
      json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects; 
      config.Formatters.Remove(config.Formatters.XmlFormatter); 

      config.Routes.MapHttpRoute(
       name: "DefaultApi", 
       // routeTemplate: "api/{controller}/{id}", 
       routeTemplate: "institute/{controller}/{id}", 
       defaults: new { id = RouteParameter.Optional }   
      ); 

      //change xml to JSON output 
      // config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); 

     } 
    } 
} 

StudentController.cs

using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Data.Entity; 
using System.Data.Entity.Infrastructure; 
using System.Linq; 
using System.Net; 
using System.Net.Http; 
using System.Web.Http; 
using System.Web.Http.Description; 
using WebAPI; 

namespace WebAPI.Controllers 
{ 
    public class StudentsController : ApiController 
    { 
     private InstituteEntities db = new InstituteEntities(); 

     // GET: api/Students 
     public IQueryable<Student> GetStudents() 
     { 
      return db.Students; 
     } 

     // GET: api/Students/5 
     [ResponseType(typeof(Student))] 
     public IHttpActionResult GetStudent(int id) 
     { 
      Student student = db.Students.Find(id); 
      if (student == null) 
      { 
       return NotFound(); 
      } 

      return Ok(student); 
     } 

     // PUT: api/Students/5 
     [ResponseType(typeof(void))] 
     public IHttpActionResult PutStudent(int id, Student student) 
     { 
      if (!ModelState.IsValid) 
      { 
       return BadRequest(ModelState); 
      } 

      if (id != student.Id) 
      { 
       return BadRequest(); 
      } 

      db.Entry(student).State = EntityState.Modified; 

      try 
      { 
       db.SaveChanges(); 
      } 
      catch (DbUpdateConcurrencyException) 
      { 
       if (!StudentExists(id)) 
       { 
        return NotFound(); 
       } 
       else 
       { 
        throw; 
       } 
      } 

      return StatusCode(HttpStatusCode.NoContent); 
     } 

     // POST: api/Students 
     [ResponseType(typeof(Student))] 
     public IHttpActionResult PostStudent(Student student) 
     { 
      if (!ModelState.IsValid) 
      { 
       return BadRequest(ModelState); 
      } 

      db.Students.Add(student); 

      try 
      { 
       db.SaveChanges(); 
      } 
      catch (DbUpdateException) 
      { 
       if (StudentExists(student.Id)) 
       { 
        return Conflict(); 
       } 
       else 
       { 
        throw; 
       } 
      } 

      return CreatedAtRoute("DefaultApi", new { id = student.Id }, student); 
     } 

     // DELETE: api/Students/5 
     [ResponseType(typeof(Student))] 
     public IHttpActionResult DeleteStudent(int id) 
     { 
      Student student = db.Students.Find(id); 
      if (student == null) 
      { 
       return NotFound(); 
      } 

      db.Students.Remove(student); 
      db.SaveChanges(); 

      return Ok(student); 
     } 

     protected override void Dispose(bool disposing) 
     { 
      if (disposing) 
      { 
       db.Dispose(); 
      } 
      base.Dispose(disposing); 
     } 

     private bool StudentExists(int id) 
     { 
      return db.Students.Count(e => e.Id == id) > 0; 
     } 
    } 
} 

の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> 
    <appSettings></appSettings> 
    <system.web> 
    <compilation debug="true" targetFramework="4.5.2" /> 
    <httpRuntime targetFramework="4.5.2" /> 
    </system.web> 
    <system.webServer> 
    <modules runAllManagedModulesForAllRequests="true"> 
     <remove name="WebDAVModule"/> 
     <!-- ADD THIS --> 
    </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> 
    </system.webServer> 
    <runtime> 
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> 
     <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> 
    <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> 
    <connectionStrings> 
    <add name="InstituteEntities" connectionString="metadata=res://*/Institute.csdl|res://*/Institute.ssdl|res://*/Institute.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=BPWSVR01;initial catalog=Institute;persist security info=True;user id=sa;password=sa;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> 
    </connectionStrings> 
    <entityFramework> 
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> 
     <parameters> 
     <parameter value="mssqllocaldb" /> 
     </parameters> 
    </defaultConnectionFactory> 
    <providers> 
     <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> 
    </providers> 
    </entityFramework> 
</configuration> 

私のエラーは以下の通りです:

{ 
    "$id": "1", 
    "Message": "An error has occurred.", 
    "ExceptionMessage": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.", 
    "ExceptionType": "System.InvalidOperationException", 
    "StackTrace": null, 
    "InnerException": { 
     "$id": "2", 
     "Message": "An error has occurred.", 
     "ExceptionMessage": "The ADO.NET provider with invariant name 'System.Data.SqlClient' is either not registered in the machine or application config file, or could not be loaded. See the inner exception for details.", 
     "ExceptionType": "System.ArgumentException", 
     "StackTrace":" at System.Data.Entity.Infrastructure.DependencyResolution.DefaultProviderFactoryResolver.<GetService>b__0(ArgumentException e, String n) 
      at System.Data.Entity.Infrastructure.DependencyResolution.DefaultProviderFactoryResolver.GetService(Type type, Object key, Func`3 handleFailedLookup) 
      at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) 
      at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext() 
      at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate) 
      at System.Data.Entity.Infrastructure.DependencyResolution.RootDependencyResolver.GetService(Type type, Object key) 
      at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext() 
      at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate) 
      at System.Data.Entity.Infrastructure.DependencyResolution.CompositeResolver`2.GetService(Type type, Object key) 
      at System.Data.Entity.Infrastructure.DependencyResolution.DbDependencyResolverExtensions.GetService[T](IDbDependencyResolver resolver, Object key) 
      at System.Data.Entity.Core.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString) 
      at System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection) 
      at System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, AppConfig config) 
      at System.Data.Entity.Internal.LazyInternalConnection.Initialize()" 
    } 
} 
+0

は、あなたのAPIメソッドを投稿し、私はあなたの問題を考えますシリアル化ではなく、代わりにエンティティフレームワークです。値を返す前にクエリを作成し、エラーが発生したかどうかを確認してください。 –

+0

@ JGEstevez ..私はちょうどAPIを追加しました。 Plsは私が一見を助ける。おかげさまで 私はこのURLを使用して実行し、取得することができます。 ます。http:// localhostを:18289 /機関/学生 が、私はIIS上で展開した後: ます。http:// localhostの/ API /機関/学生 エラーが来ましたでる – coder

答えて

0

内部例外を見てみましょう。

The ADO.NET provider with invariant name 'System.Data.SqlClient' is either not registered in the machine or application config file

あなたの問題は、Entity Frameworkのに関連していることは明らかである:あなたのサーバーに正しくSystem.Data.SqlClientアセンブリを展開されていません。

これらの質問は、あなたがこの問題を解決する方法を見つけるのに役立つことがあります。私はあなたがそこに何をしたか見ることができるように

関連する問題