ASP.NET核心 - 当前上下文中不存在名称"JsonRequestBehavior"

nam*_*nam 38 c# asp.net json visual-studio-2015 asp.net-core

在我的ASP.NET核心(.NET Framework)项目中,我在以下的Controller Action方法中遇到了错误.我可能缺少什么?或者,有什么工作吗?:

    public class ClientController : Controller
    {
      public ActionResult CountryLookup()
      {
        var countries = new List<SearchTypeAheadEntity>
            {
                new SearchTypeAheadEntity {ShortCode = "US", Name = "United States"},
                new SearchTypeAheadEntity {ShortCode = "CA", Name = "Canada}
            };

        return Json(countries, JsonRequestBehavior.AllowGet);
      }
    }
Run Code Online (Sandbox Code Playgroud)

更新:

请注意以下@NateBarbettini的评论:

  1. JsonRequestBehavior 已在ASP.NET Core 1.0中弃用.
  2. 在下面的@Miguel接受的回复中,return typeaction方法does not特别需要是JsonResult类型.ActionResult或IActionResult也可以.

小智 38

返回Json格式的数据:

public class ClientController : Controller
{
    public JsonResult CountryLookup()
    {
         var countries = new List<SearchTypeAheadEntity>
         {
             new SearchTypeAheadEntity {ShortCode = "US", Name = "United States"},
             new SearchTypeAheadEntity {ShortCode = "CA", Name = "Canada}
         };

         return Json(countries);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 它并不特别需要返回类型`JsonResult`.`ActionResult`或`IActionResult`也有效. (6认同)

Rav*_*ana 8

在代码中它的替换要JsonRequestBehavior.AllowGetnew Newtonsoft.Json.JsonSerializerSettings()

它的工作与 JsonRequestBehavior.AllowGet

public class ClientController : Controller
{
  public ActionResult CountryLookup()
  {
    var countries = new List<SearchTypeAheadEntity>
        {
            new SearchTypeAheadEntity {ShortCode = "US", Name = "United States"},
            new SearchTypeAheadEntity {ShortCode = "CA", Name = "Canada"}
        };

    return Json(countries, new Newtonsoft.Json.JsonSerializerSettings());
  }
}
Run Code Online (Sandbox Code Playgroud)