2017-08-12 3 views
0

Ich bin darauf für ein paar Stunden ratlos.Nur Json zurückgegeben werden, wenn WebApi 2 und EntityFramework

Ich benutze WebApi 2 und Entity Framework 6.1.3. Ich folge diesem Tutorial: https://docs.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/

Ich möchte nur json zurückgeben. Wenn ich die URL http://localhost:11440/Api/Contacts drücke. Ich erhalte folgenden Fehler: Der 'ObjectContent`1' Typ konnte den Antworttext für den Inhaltstyp 'application/xml; charset = utf-8 '.

Ich habe folgende Modelle und Controller definiert:

Address.cs

namespace Blah_Application.Models 
{ 
    public class Address 
    { 
     public int AddressID { get; set; } 

     public int ContactID { get; set; } 

     public string Street { get; set; } 

     public string City { get; set; } 

     public string State { get; set; } 

     public string Country { get; set; } 

     public string ZipCode { get; set; } 

     public double Latitude { get; set; } 

     public double Longitude { get; set; } 

     public virtual Contact Contact { get; set; } 
    } 
} 

Contact.cs

using System.Collections.Generic; 

namespace Blah_Application.Models 
{ 
    public class Contact 
    { 
     public Contact() 
     { 
      Phones = new HashSet<Phone>(); 
      Addresses = new HashSet<Address>(); 
     } 

     public int ContactID { get; set; } 

     public string Name { get; set; } 

     public string Company { get; set; } 

     public bool Favorite { get; set; } 

     public string SmallImageUrl { get; set; } 

     public string LargeImageUrl { get; set; } 

     public string Email { get; set; } 

     public string Website { get; set; } 

     public string BirthDate { get; set; } 

     public virtual ICollection<Phone> Phones { get; set; } 

     public virtual ICollection<Address> Addresses { get; set; } 
    } 
} 

Phone.cs

namespace Ecitslos_Application.Models 
{ 
    public enum PhoneType { Home, Work, Mobile} 

    public class Phone 
    { 
     public int PhoneID {get; set;} 

     public int ContactID { get; set; } 

     public PhoneType PhoneType { get; set; } 

     public string Number { get; set; } 

     public virtual Contact Contact { get; set; } 
    } 
} 

ContactsController.cs

using System.Data.Entity; 
using System.Data.Entity.Infrastructure; 
using System.Linq; 
using System.Net; 
using System.Web.Http; 
using System.Web.Http.Description; 
using Blah_Application.Models; 

namespace Ecitslos_Application.Controllers 
{ 
    public class ContactsController : ApiController 
    { 
     private Ecitslos_ApplicationContext db = new 
     Ecitslos_ApplicationContext(); 

     // GET: api/Contacts 
     public IQueryable<Contact> GetContacts() 
     { 
      return db.Contacts; 
     } 

     // GET: api/Contacts/5 
    [ResponseType(typeof(Contact))] 
    public IHttpActionResult GetContact(int id) 
    { 
     Contact contact = db.Contacts.Find(id); 
     if (contact == null) 
     { 
      return NotFound(); 
     } 

     return Ok(contact); 
    } 

    // PUT: api/Contacts/5 
    [ResponseType(typeof(void))] 
    public IHttpActionResult PutContact(int id, Contact contact) 
    { 
     if (!ModelState.IsValid) 
     { 
      return BadRequest(ModelState); 
     } 

     if (id != contact.ContactID) 
     { 
      return BadRequest(); 
     } 

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

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

     return StatusCode(HttpStatusCode.NoContent); 
    } 

    // POST: api/Contacts 
    [ResponseType(typeof(Contact))] 
    public IHttpActionResult PostContact(Contact contact) 
    { 
     if (!ModelState.IsValid) 
     { 
      return BadRequest(ModelState); 
     } 

     db.Contacts.Add(contact); 
     db.SaveChanges(); 

     return CreatedAtRoute("DefaultApi", new { id = contact.ContactID }, contact); 
    } 

    // DELETE: api/Contacts/5 
    [ResponseType(typeof(Contact))] 
    public IHttpActionResult DeleteContact(int id) 
    { 
     Contact contact = db.Contacts.Find(id); 
     if (contact == null) 
     { 
      return NotFound(); 
     } 

     db.Contacts.Remove(contact); 
     db.SaveChanges(); 

     return Ok(contact); 
    } 

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

    private bool ContactExists(int id) 
    { 
     return db.Contacts.Count(e => e.ContactID == id) > 0; 
    } 
    } 
} 

Antwort

0

Sie müssen das XML-Formatierungsprogramm deaktivieren, das standardmäßig konfiguriert ist. Fügen Sie der WebApiConfig-Klasse die folgende Zeile hinzu:

public static class WebApiConfig { 
    public static void Register(HttpConfiguration config) { 
     //route config etc. goes here 

     //disable xml serialization 
     config.Formatters.Remove(config.Formatters.XmlFormatter); 

     //prevent infinite recusion 
     config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; 
    } 
} 
+0

das funktioniert nicht für mich. Wenn ich versuche, bekomme ich Fehler: Selbstreferenzierungsschleife erkannt für Eigenschaft 'Kontakt' mit Typ 'System.Data.Entity.DynamicProxies.Contact_F0D869DA35A5D79D9FC7459ECA71E46F93E7CACF4EB08F9DCCF7A7DCCF99E1D3 – hikerclimb

+0

@hikerclimb Das ist ein separates Problem von der Rückgabe nur JSON. Ich habe meine Antwort so bearbeitet, dass sie eine zweite Konfigurationseinstellung enthält. – user2880616

+0

@hikerclimb ist es, weil Sie "Kontakt" in "Telefon" haben und dann "Telefon" in "Kontakt" instanziieren? –

0

Wie mache ich das in meinem Projekt ist das folgende. Hoffe, Sie können einen Zeiger in die richtige Richtung bekommen.

// GET: api/Contacts/5 
    <Route("~/api/Contacts/{id}")> 
    <HttpGet> 
    public HttpResponseMessage GetContact(int id) 
    { 
     Contact contact = db.Contacts.Find(id); 
     if (contact == null) 
     { 
      Return Request.CreateResponse(HttpStatusCode.NotFound, "Contact Id not found", Configuration.Formatters.JsonFormatter); 
     } 
Return Request.CreateResponse(HttpStatusCode.OK, contact, Configuration.Formatters.JsonFormatter); 

    } 

Außerdem haben Sie Contact in Phone und dann sind Sie Phone in Contact instanziieren. Dies kann eine zyklische Abhängigkeit erzeugen.

Verwandte Themen