我正在创建一个post API来将数据存储在数据库中。我创建了一个类并将类成员数据添加到模型中,但是我收到了错误
给出错误 - 无法从'System.Web.Mvc.JsonRequestBehavior'转换为'Newtonsoft.Json.JsonSerializerSettings'
public ActionResult AddTemprature([FromBody]tempretureViewModel paramTemplate)
{
try
{
DateTime currentTime = DateTime.Now;
using (smartpondEntities DB = new smartpondEntities())
{
WebApi.Temperature temptable = new WebApi.Temperature();
// and you need paramTemplate props to template object
DB.Temperatures.Add(temptable);
DB.SaveChanges();
return Json(true, JsonRequestBehavior.AllowGet);
}
}
catch (Exception Ex)
{
}
return Json(false, JsonRequestBehavior.AllowGet);
}
public class tempretureViewModel
{
public decimal? temp1 { get; set; }
public decimal? PHValue { get; set; }
public decimal? DOValue { get; set; }
public DateTime? currentTime { get; set; }
}
WebApiConfig
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
}
答案 0 :(得分:0)
它不是关于asp.net,json实体框架,模型视图控制器,asp.net-web-api2。关于c#。 WebApi.Controllers.tempretureViewModel'和'WebApi.Temperature'“不同的类型。
public ActionResult AddTemprature([FromBody]tempretureViewModel paramTemplate)
{
try
{
currentTime = DateTime.Now;
using (smartpondEntities DB = new smartpondEntities())
{
WebApi.Temperature temptable = new WebApi.Temperature();
// and you need to set paramTemplate props to template object
DB.Temperatures.Add(temptable);
DB.SaveChanges();
return Json(true, JsonRequestBehavior.AllowGet);
}
}
catch (Exception Ex)
{
}
return Json(false, JsonRequestBehavior.AllowGet);
}
更新:WebApiConfig.cs
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
答案 1 :(得分:0)
在类之上使用命名空间而不是使用类 我用粗体标记了。 WebApi.Temperature temptable = new WebApi.Temperature(); 添加名称空间
public ActionResult AddTemprature([FromBody]tempretureViewModel paramTemplate)
{
try
{
DateTime currentTime = DateTime.Now;
using (smartpondEntities DB = new smartpondEntities())
{
**WebApi.Temperature temptable = new WebApi.Temperature();**
// and you need paramTemplate props to template object
DB.Temperatures.Add(temptable);
DB.SaveChanges();
return Json(true, JsonRequestBehavior.AllowGet);
}
}
catch (Exception Ex)
{
}
return Json(false, JsonRequestBehavior.AllowGet);
}
public class tempretureViewModel
{
public decimal? temp1 { get; set; }
public decimal? PHValue { get; set; }
public decimal? DOValue { get; set; }
public DateTime? currentTime { get; set; }
}