我已经搜索解决方案好几个小时了,但找不到我的问题的答案。 我想将post方法发送到网络api,并且我首先使用这些json内容在邮递员上尝试过,并且可以正常工作。
{
"ETickets": [
{
"TicketName": "Weekend - Regular Day Pass",
"TicketAccessType": "PA",
"TicketGuest": "RDP",
"IsWeekday": true
},
{
"TicketName": "Weekend - Regular Day Pass",
"TicketAccessType": "PA",
"TicketGuest": "RDP",
"IsWeekday": true
}
],
"TransactDetails": {
"CompanyCode": "ONLINE",
"Surname": "Dela Cruz",
"FirstName": "Juan",
"BookingReference": "1113",
"BookingDate": "2018-08-16T11:31:20:04"
}
}
但是,当我尝试以编码方式进行操作时,无法使其正常工作。调试时显示500个内部服务器错误。 这是错误屏幕截图:
以下是与我的问题相关的一些代码:
TransactionDetailsViewModel finale = new TransactionDetailsViewModel();
finale.TransacDetails = transacDetail;
finale.ETickets = lsTickets.ToArray();
client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", System.Web.HttpContext.Current.Session["WebApiAccessToken"].ToString());
HttpResponseMessage responseMessage = await client.PostAsJsonAsync(url + "api/Transaction/SendTransaction/", finale);
这是我使用的模型:
public class TransactionDetailsViewModel
{
public TransactionDetails TransacDetails { get; set; }
public TicketDetailsModel[] ETickets { get; set; }
}
public class TransactionDetails
{
public string CompanyCode { get; set; }
public string Surname { get; set; }
public string FirstName { get; set; }
public string BookingReference { get; set; }
public DateTime? BookingDate { get; set; }
}
public class TicketDetailsModel
{
public string TicketAccessType { get; set; }
public string TicketGuest { get; set; }
public string TicketName { get; set; }
public bool IsWeekday { get; set; }
}
我是否以正确的格式发送数据或进行一些调整以使其在发送到PostAsJsonAsync
时起作用?
任何帮助将不胜感激。谢谢。
答案 0 :(得分:1)
请修改您的代码,就像
var data = new StringContent(JsonConvert.SerializeObject(finale, Encoding.UTF8, "application/json"));
HttpResponseMessage responseMessage = await client.PostAsJsonAsync("api/Transaction/SendTransaction/", data);
或者您可以发出请求,然后像这样发送
HttpResponseMessage response = null;
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Post, url+"/api/Transaction/SendTransaction"))
{
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", System.Web.HttpContext.Current.Session["WebApiAccessToken"].ToString());
var data = new StringContent(JsonConvert.SerializeObject(finale, Encoding.UTF8, "application/json"));
request.Content = data;
response = await client.SendAsync(request);
}
}
答案 1 :(得分:1)
请尝试在下面的行中发布数据
httpClient.PostAsync(url + "/api /Transaction/SendTransaction/", new StringContent(JsonConvert.SerializeObject(finale).ToString(), Encoding.UTF8, "application/json")).Result;