【发布时间】:2016-11-07 14:42:20
【问题描述】:
我正在尝试使用 HTTPClient 发布一些数据。在简单地获取 JSON 格式的数据时,我设法使用了以下代码,但它似乎不适用于 POST。
这是我正在使用的代码:
public static async Task<SwipeDetails> SaveSwipesToCloud()
{
//get unuploaded swips
IEnumerable<SwipeDetails> swipesnotsved = SwipeRepository.GetUnUploadedSwipes();
foreach (var item in swipesnotsved)
{
//send it to the cloud
Uri uri = new Uri(URL + "SaveSwipeToServer" + "?locationId=" + item.LocationID + "&userId=" + item.AppUserID + "&ebCounter=" + item.SwipeID + "&dateTimeTicks=" + item.DateTimeTicks + "&swipeDirection=" + item.SwipeDirection + "&serverTime=" + item.IsServerTime );
HttpClient myClient = new HttpClient();
var response = await myClient.GetAsync(uri);
//the content needs to update the record in the SwipeDetails table to say that it has been saved.
var content = await response.Content.ReadAsStringAsync();
}
return null;
}
这是它试图联系的方法。如您所见,该方法还返回一些 JSON 格式的数据,以及一个 POST,它还返回一些我需要能够使用的数据:
[HttpPost]
public JsonResult SaveSwipeToServer(int locationId, int userId, int ebCounter, long dateTimeTicks, int swipeDirection, int serverTime)
{
bool result = false;
string errMsg = String.Empty;
int livePunchId = 0;
int backupPunchId = 0;
IClockPunch punch = null;
try
{
punch = new ClockPunch()
{
LocationID = locationId,
Swiper_UserId = userId,
UserID = ebCounter,
ClockInDateTime = DateTimeJavaScript.ConvertJavascriptDateTime(dateTimeTicks),
ClockedIn = swipeDirection.Equals(1),
};
using (IDataAccessLayer dal = DataFactory.GetFactory())
{
DataAccessResult dalResult = dal.CreatePunchForNFCAPI(punch, out livePunchId, out backupPunchId);
if (!dalResult.Result.Equals(Result.Success))
{
throw dalResult.Exception;
}
}
result = true;
}
catch (Exception ex)
{
errMsg = "Something Appeared to go wrong when saving punch information to the horizon database.\r" + ex.Message;
}
return Json(new
{
result = result,
punchDetails = punch,
LivePunchId = livePunchId,
BackUpPunchId = backupPunchId,
timeTicks = DateTimeJavaScript.ToJavaScriptMilliseconds(DateTime.UtcNow),
errorMessage = errMsg
}
,JsonRequestBehavior.AllowGet);
}
目前存储在“内容”中的数据只是一条错误消息。
【问题讨论】:
-
如果您通过查询字符串传递所有数据,您可以将您的操作方法定义为 HttpGet 操作。您的请求没有发回任何数据。
-
你有例子吗?请求最后返回 Json 数据。
-
如果您提供我可以调用 SaveSwipesToCloud 的 URI,我可以给您示例。我需要 URI 来测试我为你编写的代码
-
如果你想 POST,简单的答案是使用
PostAsync(),而不是GetAsync(),这自然是一个GET。 -
@SamiKuhmonen 是的,但他需要发布数据而不仅仅是调用 Post,这就是我想在提供解决方案之前测试的内容
标签: c# visual-studio xamarin http-post xamarin.forms