【问题标题】:Return JSON from WebApi controller using Included properties使用 Included 属性从 WebApi 控制器返回 JSON
【发布时间】: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


    【解决方案1】:

    我想了很久才明白:

    [System.Web.Mvc.HttpGet]
    public IHttpActionResult GetEmployee()
    {
        var employee= db.Employee.Include(x => x.Department);
        return Json(employee, new JsonSerializerSettings(){ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-23
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多