我有视觉工作室2017与系统中的以下Xamarin版本 .
Microsoft Visual Studio Professional 2017版本15.6.1 VisualStudio.15.Release / 15.6.1 27428.2002 Microsoft .NET Framework版本4.7.02556 Xamarin 4.9.0.749(9b0fce36d)Visual Studio扩展,用于为Xamarin.iOS和Xamarin.Android启用开发 . Xamarin Designer 4.10.58(cee1369d0)Visual Studio扩展,用于在Visual Studio中启用Xamarin Designer工具 . Xamarin.Android SDK 8.2.0.15(HEAD / 22d97e153)Xamarin.Android参考组件和MSBuild支持 . Xamarin.iOS和Xamarin.Mac SDK 11.8.0.20(1c6f300)Xamarin.iOS和Xamarin.Mac参考组件和MSBuild支持 . 我已经创建了简单的Xamarin android,并添加了一些.net类库作为参考 .
我尝试使用xamarin应用程序发布一些数据,但总是在webapi中获取null值 .
在c#下面的WebApi代码
public class DataPostController : ApiController
{
[HttpPost]
public string Post(CSVItem data)
{
// CSVData data = JsonConvert.DeserializeObject<CSVData>(json);
try
{
string error = string.Empty;
if (data != null)
{
error += ImportService.clsGlobal.AddItem(data.SerialNumber, data);
}
error = string.IsNullOrEmpty(error) ? "-1" : error;
return error;
}
catch (Exception ex)
{
return ex.Message;
}
}
public string Get()
{
return "Hello";
}
}
使用xamarin app调用post方法
CSVItem item = GetItems();
var url = string.Format("{0}/{1}?", "http://myurl.com", "api/DataPost");
string sContentType = "application/json"; // or application/xml
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "cHRlc3Q5OnB1bXB0ZXN0OUAxMjM0NTY=");
var oTaskPostAsync = client.PostAsync(url, new StringContent(item.ToString(), Encoding.UTF8, sContentType));
var res = oTaskPostAsync.ContinueWith((oHttpResponseMessage) =>
{
Task<string> r1 = oHttpResponseMessage.Result.Content.ReadAsStringAsync();
var strResult = r1.Result;
// response of post here
Pt9Log.WriteLog("HistoryDownload PostCSV end. StatusCode" + oTaskPostAsync.Result.StatusCode.ToString());
Pt9Log.WriteLog("HistoryDownload PostCSV end. Result===" + oTaskPostAsync.Result.ToString());
Pt9Log.WriteLog("HistoryDownload PostCSV end. Post Response===" + strResult);
if (oTaskPostAsync.Result.StatusCode == System.Net.HttpStatusCode.OK)
result = true;
else
result = false;
});
模型类在应用程序中使用与在webApi中相同的两侧相同 .
public class CSVItem
{
public string SerialNumber { get; set; }
public double Input1 { get; set; }
public double Input2 { get; set; }
public double Input3 { get; set; }
public double Input4 { get; set; }
public double Input5 { get; set; }
public double Input6 { get; set; }
public string Input7 { get; set; }
public double Input8 { get; set; }
}
1 回答
您应该使用
JsonConvert.SerializeObject()
convertitem
到JSON,而不是使用item.ToString()
.例如:
您可以参考Consuming a RESTful Web Service以获取更多信息 .