gpt4 book ai didi

android - Web API 服务器 Controller 未获取参数

转载 作者:行者123 更新时间:2023-11-29 17:23:24 24 4
gpt4 key购买 nike

我从 Android 应用程序发送 JSON 数据。在服务器端,我遇到了问题 - Web API 服务器 Controller 没有获取参数。从客户端我发送这样的 json 数据:

{   "TypeID ": "1",
"FullName": "Alex",
"Title": "AlexTitle",
"RegionID": "1",
"CityID ": "1",
"Phone1": "+7(705)105-78-70"
}

感谢任何帮助,如果您有一些信息,想法请告诉我,谢谢!这是 Controller

 [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");
}

}

最佳答案

你的问题很简单。您正在发送一个 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;}
}

然后,将您的 Action 签名更改为:

[FromBody]RequisitionViewModel requisition)

您也不需要代码中的所有转换:

postReq.FullName = requisition.FullName;
postReq.CityID = requisition.CityID;
//other fields...

关于android - Web API 服务器 Controller 未获取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35699089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com