严重程度代码说明项目文件行无法转换为' System.Web.Mvc.JsonRequestBehavior' to' Newtonsoft.Json.JsonSerializerSettings'

时间:2017-05-22 11:42:22

标签: json asp.net-mvc asp.net-web-api

无法转换为System.Web.Mvc.JsonRequestBehavior' to' Newtonsoft.Json.JsonSerializerSettings'

 public JsonResult Get()
        {
            try
            {
                using (smartpondEntities DB = new smartpondEntities())
                {
                    var pond = DB.Temperatures.OrderByDescending(x => x.WaterTemperature).FirstOrDefault();
                    return Json(new { success = true, sensorsdata = new { id = pond.WaterTemperature, CurrentTime = pond.CreatedDate } }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception Ex)
            {
            }
            return Json(new { success = false }, JsonRequestBehavior.AllowGet);
        }

1 个答案:

答案 0 :(得分:0)

Web API控制器中Json方法的第二个参数分配不正确,因为ApiController Json method需要JsonSerializerSettings作为第二个参数:

protected internal JsonResult<T> Json<T>(T content, JsonSerializerSettings serializerSettings)
{
    ......
}

Json method的MVC控制器副本如下所示:

protected internal JsonResult Json(object data, JsonRequestBehavior behavior)
{
   ......
}

在这种情况下,如果上面包含Get方法的控制器类扩展ApiController,则需要将2 return Json个语句更改为return new JsonResult,如下所示:

public class ControllerName : ApiController
{
    public JsonResult Get()
    {
        try
        {
            using (smartpondEntities DB = new smartpondEntities())
            {
                var pond = DB.Temperatures.OrderByDescending(x => x.WaterTemperature).FirstOrDefault();

                // return JsonResult here
                return new JsonResult()
                {
                    Data = new { success = true, sensorsdata = new { id = pond.WaterTemperature, CurrentTime = pond.CreatedDate }},
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
        }
        catch (Exception Ex)
        {
        }

        // return JsonResult here
        return new JsonResult()
        {
            Data = new { success = false },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }
}

如果您想在返回JSON时使用MVC控制器,请从ApiController命名空间将Controller更改为System.Web.Mvc类并保留return Json(...)

类似问题:

JSON return error with ASP