只希望在使用 WebApi 2 和 EntityFramework 时返回 json



我被这个难倒了几个小时。

我正在使用 WebApi 2 和实体框架 6.1.3。我正在遵循本教程: https://learn.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/

我只想返回 json。当我点击网址 http://localhost:11440/Api/Contacts 时。我收到以下错误: "对象内容"1"类型无法序列化内容类型"应用程序/xml"的响应正文;字符集=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; }
}
}

联系方式.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; }
}
}

电话.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; }
}
}

联系人控制器.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;
}
}
}

您需要禁用默认配置的 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;
}
}

我在项目中执行此操作的方式如下。 希望你能得到正确方向的指针。

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

此外,您在Phone中具有Contact,然后在Contact中实例化Phone。 这可能会产生循环依赖关系。

相关内容

  • 没有找到相关文章

最新更新