以下是我如何在几乎任何项目(包括 Xamarin 项目)中使用此服务。
首先,删除 Global.asax 文件中这样的行:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
一般来说,这是不好的做法。您至少希望有可用的 XML 和 JSON 格式化程序,因为在宁静的环境中,由消费者决定他们需要/想要什么类型的序列化。
接下来,我将使用System.Net.Http.HttpClient
与此服务交互的类。
从此时起,与 Web Api 服务进行交互就相当简单了。这里有些例子。
public async List<Dept> GetDepts()
{
using(var client = new HttpClient())
{
client.BaseAddress = new Uri("http://<ipAddress:port>/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return await client.GetAsync("/api/dept");
}
}
public async Task<Dept> GetDept(int id)
{
using(var client = new HttpClient())
{
client.BaseAddress = new Uri("http://<ipAddress:port>/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var result = await client.GetAsync(string.format("/api/dept/{0}", id));
return JsonConvert.DeserializeObject<Dept>(await result.Content.ReadAsStringAsync());
}
}
public async Task AddDept(Dept dept)
{
using(var client = new HttpClient())
{
client.BaseAddress = new Uri("http://<ipAddress:port>/");
await client.PostAsJsonAsync("/api/dept", dept);
}
}
public async Task UpdateDept(Dept dept)
{
using(var client = new HttpClient())
{
client.BaseAddress = new Uri("http://<ipAddress:port>/");
await client.PutAsJsonAsync(string.format("/api/dept/{0}", dept.no), dept);
}
}
public async Task DeleteDept(int id)
{
using(var client = new HttpClient())
{
client.BaseAddress = new Uri("http://<ipAddress:port>/");
client.DeleteAsync(string.format("/api/dept/{0}", id));
}
}
无论如何,这应该能让你朝着正确的方向开始。这绝对可以得到清理,而且是我徒手写的,所以可能会有一些拼写错误。
Update
更新您的 MainActivity.cs
代替int id = Convert.ToInt32(txtValue1)
Use
int id = Convert.ToInt32(txtValue1.Text);
代替GetButton.Click += GetDept(id);
Use
GetButton.Click += async (sender, args) => {
var dept = await GetDept(id);
No.Text = dept.no;
Name.Text = dept.name
}