【发布时间】:2019-09-22 03:02:23
【问题描述】:
我想从 Web Api 2 控制器返回 JSON。我当前的代码不适用于包含的属性。我的get方法是:
[System.Web.Mvc.HttpGet]
public IQueryable<Employee> GetEmployee()
{
return db.Employee.Include(x=>x.Department);
}
我已将此行添加到我的 WebApiConfig:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
在获取时我收到此错误:
“ObjectContent`1”类型未能序列化响应正文 内容类型'应用程序/json; charset=utf-8'。
当我使用标准控制器(不是 Api 控制器)时,我的代码是:
[HttpGet]
public ActionResult GetCountries()
{
var countries = JsonConvert.SerializeObject(db.Countries.Include(x => x.Regions), Formatting.None, new JsonSerializerSettings() {ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore });
return Content(countries, "application/json");
}
但是 Content() 是特定于 Controller 类的,我猜它不能在 WebApi Controllers 中使用。
所需的 JSON 结构是:
[
{
"Iso3": "AL",
"CountryNameEnglish": "Alaska",
"Regions": [
{
"RegionCode": "AL1",
"Iso3": "AL",
"RegionNameEnglish": "Alaskan Region 1"
},
{
"RegionCode": "AL2",
"Iso3": "AL",
"RegionNameEnglish": "Alaskan Region 2"
}
]
}
]
有人知道如何处理吗?
【问题讨论】:
标签: asp.net json entity-framework