0

私はこれに数時間困惑しています。

WebApi 2 と Entity Framework 6.1.3 を使用しています。このチュートリアルに従っています: https://docs.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/

jsonのみを返したいと思います。URL http://localhost:11440/Api/Contactsをヒットすると。次のエラーが表示されます: 'ObjectContent`1' タイプは、コンテンツ タイプ 'application/xml; の応答本文をシリアル化できませんでした。charset=utf-8'.

次のモデルとコントローラーが定義されています。

アドレス.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;
    }
    }
}
4

2 に答える 2

0

私のプロジェクトでこれを行う方法は次のとおりです。正しい方向へのポインターを取得できることを願っています。

 // 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);

    }

また、 を持っていてContact、 でPhoneインスタンス化PhoneしていますContact。これにより、循環依存が発生する可能性があります。

于 2017-08-14T02:04:11.557 に答える