只有在使用WebApi 2和EntityFramework时才需要返回json

时间:2017-08-12 18:07:52

标签: json entity-framework-6 webapi2

我被困了几个小时。

我正在使用WebApi 2和Entity Framework 6.1.3。我正在关注本教程: preg_replace

我想只返回json。当我点击网址https://docs.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/时。我收到以下错误: 'ObjectContent`1'类型无法序列化内容类型'application / xml的响应主体;字符集= UTF-8' 。

我定义了以下模型和控制器:

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;
    }
    }
}

2 个答案:

答案 0 :(得分:0)

您需要禁用默认配置的XML格式化程序。将以下行添加到WebApiConfig类:

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;
    }
}

答案 1 :(得分: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。这可能会产生循环依赖。