【问题标题】:while using JsonRequestBehavior in web api giving error saying cannot convert to json.serializer在 Web api 中使用 JsonRequestBehavior 时出现错误提示无法转换为 json.serializer
【发布时间】:2017-05-22 18:48:47
【问题描述】:

我收到以下编译错误:

cannot convert from 'System.Web.Mvc.JsonRequestBehavior' to 'Newtonsoft.Json.JsonSerializerSettings'

代码

public class PondController : ApiController
{
    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);
    }
}

【问题讨论】:

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


    【解决方案1】:

    您正在尝试在 ASP.NET WebAPI 控制器中使用来自 ASP.NET MVC 的代码 sn-p。在 WebAPI 中,结果和方法具有不同的签名。请尝试以下操作:

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

    【讨论】:

      猜你喜欢
      • 2017-11-03
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-21
      相关资源
      最近更新 更多