我从Android应用发送 JSON数据 。在服务器端我有问题 - Web API服务器 控制器没有获取参数。从客户端我发送json数据如下:
{ "TypeID ": "1",
"FullName": "Alex",
"Title": "AlexTitle",
"RegionID": "1",
"CityID ": "1",
"Phone1": "+7(705)105-78-70"
}
任何帮助表示感谢,如果您有一些信息,请告诉我,谢谢! 这是控制器
[System.Web.Http.HttpPost]
public HttpResponseMessage PostRequisition([FromBody]string requisition)
{
Requisition postReq = new Requisition();
if (!String.IsNullOrEmpty(requisition))
{
dynamic arr = JValue.Parse(requisition);
//PostReq model = JsonConvert.DeserializeObject<PostReq>(requisition);
postReq.FullName = arr.FullName;
postReq.CityID = Convert.ToInt32(arr.CityID);
postReq.RegionID = Convert.ToInt32(arr.RegionID);
postReq.TypeID = Convert.ToInt32(arr.TypeID);
postReq.UserID = 8;
postReq.Title = arr.Title;
postReq.Date = Convert.ToDateTime(arr.Date, CultureInfo.CurrentCulture);
postReq.Decription = arr.Description;
postReq.Phone1 = arr.Phone1;
postReq.Activate = false;
postReq.ClickCount = 0;
try
{
db.Requisition.Add(postReq);
db.SaveChanges();
Message msg = new Message();
msg.Date = DateTime.Now;
msg.Type = "POST";
msg.Text = "OK";
db.Message.Add(msg);
db.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, postReq);
}
catch (Exception ex)
{
Message msg = new Message();
msg.Date = DateTime.Now;
msg.Type = "POST";
msg.Text = "ERROR";
db.Message.Add(msg);
db.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, ex.Message);
}
}
else
{
Message msg = new Message();
msg.Date = DateTime.Now;
msg.Type = "POST";
msg.Text = "null";
db.Message.Add(msg);
db.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, "null");
}
}
答案 0 :(得分:3)
你的问题很简单。您正在发送JSON对象,但在POST操作中需要一个字符串。解决这个问题的简单方法是创建一个映射到JSON对象的类:
public class RequisitionViewModel
{
public int TypeID {get; set;}
public string FullName {get; set;}
public string Title {get; set;}
public int RegionID {get; set;}
public int CityID {get; set;}
public string Phone1 {get; set;}
}
然后,将您的操作签名更改为:
[FromBody]RequisitionViewModel requisition)
您也不需要在代码中进行所有转换:
postReq.FullName = requisition.FullName;
postReq.CityID = requisition.CityID;
//other fields...