无法转换为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);
}
答案 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(...)
。
类似问题: