我正在尝试从Winform应用程序调用API,但是却收到错误的请求错误。我认为我无法为我的帖子请求设置有效的字符串格式。
编辑:添加driverDayLogModel类代码
driveDayLogModel.cs
public class driverDayLogModel
{
public int driverId { get; set; }
public DateTime dayStartTime { get; set; }
}
API调用代码
driverDayLogModel driverDayLog = new driverDayLogModel
{
driverId = Convert.ToInt32(txtId.Text),
dayStartTime = DateTime.Now,
};
var js = new JavaScriptSerializer();
string json = JsonConvert.SerializeObject(driverDayLog);
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://127.0.0.1:54314/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsJsonAsync("api/driverdaylogs", json).Result;
if (response.IsSuccessStatusCode)
{
// Some Stuff
}
else
{
MessageBox.Show("Error Code" +
response.StatusCode + " : Message - " + response.ReasonPhrase);
}
}
我得到的Json为"{\"driverId\":1,\"dayStartTime\":\"2019-03-03T21:44:15.1912313+05:00\"}"
对于API来说,这似乎是无效的json,当我在邮递员上尝试使用相同的json时,也会导致400错误的请求错误,但必须注意的是,当我使用Json {"driverId":1,"dayStartTime":"2019-03-03T21:44:15.1912313+05:00"}
调用API时,我的请求成功了,并且在POSTMAN中得到了预期的响应。我无法在Winforms中将json转换为webapi可接受的格式
以下是Webapi的代码。
public IHttpActionResult PostDayLogs([FromBody]driverDayLogModel log)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
var driverDayLog = new driverDailyLogs();
driverDayLog.dayEndTime = DateTime.Now;
driverDayLog.dayStartTime = log.dayStartTime;
driverDayLog.driverId = log.driverId;
var max = db.driverDailyLogs.OrderByDescending(r => r.id).FirstOrDefault();
driverDayLog.id = max == null ? 1 : max.id + 1;
driverDayLog.logDate = DateTime.Now.Date;
db.driverDailyLogs.Add(driverDayLog);
db.SaveChanges();
return Ok(driverDayLog);
}
在WebApiConfig中,我有以下代码
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.Formatters.JsonFormatter
.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
在这方面请指导我。
答案 0 :(得分:0)
使用HttpClient
,您无需在将对象发送到Web Api之前将其序列化为Json。 HttpClient
将为您处理序列化。
编辑(删除了以前似乎无效的先前代码)
只需发送对象,而不是在PostAsJsonAsync
中发送Json。
driverDayLogModel driverDayLog = new driverDayLogModel
{
driverId = Convert.ToInt32(txtId.Text),
dayStartTime = DateTime.Now,
};
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://127.0.0.1:54314/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// simply put the object as the second parameter instead of a Json string
var response = client.PostAsJsonAsync("api/driverdaylogs", driverDayLog).Result;
if (response.IsSuccessStatusCode)
{
// Some Stuff
}
else
{
MessageBox.Show("Error Code" +
response.StatusCode + " : Message - " + response.ReasonPhrase);
}
}
请注意:使用.Result
将阻止您的代码,因此建议的方法是使用await
和async
,但这不在此问题/答案的范围之内。