2016-05-19 5 views
0

J'ai essayé de faire toutes les solutions possibles mais je n'ai toujours pas trouvé la bonne réponse. Ci-dessous mon code:Erreur API Web: Le type 'ObjectContent`1' n'a pas réussi à sérialiser

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> 

mon erreur est ci-dessous:

{ 
    "$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

publier votre méthode api pour que je puisse voir ce que vous avez fait là-bas, mais je pense que votre question n'est pas une sérialisation et plutôt un cadre d'entité. essayez de faire une requête avant de renvoyer des valeurs et voyez si vous avez une erreur. –

+0

@ JGEstevez..J'ai juste ajouté l'API. Pls m'aider à jeter un coup d'oeil. Merci. Je utilisé cette URL et exécuter, peut récupérer: http: // localhost: 18289/Institut/Etudiants mais après je Déployé sur IIS: http: // localhost/api/Institut/Etudiants a reçu l'erreur venir en dehors – coder

Répondre

0

Regardez l'exception interne:

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

Il est évident que votre problème est lié à Entity Framework: vous n'êtes pas correctement System.Data.SqlClient déployait ensemble sur votre serveur.

Ces questions peuvent vous aider à trouver comment résoudre ce problème: