如何在xamarin跨平台应用程序中使用Web Api

时间:2014-09-10 13:58:13

标签: android api xamarin

我创建了一个从SQL数据库中检索数据的web api。我需要在xamrin中使用web api for android和xamarin for iOS。截至目前xamarin为Android。我不知道如何根据按钮点击事件调用GET和Post方法。

这是web api

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MvcAppDept.Controllers
{
public class DeptController : ApiController
{
    // GET api/values
    public IEnumerable<Dept> Get()
    {
        AndroidAppDBEntities db = new AndroidAppDBEntities();
        var data = from dept in db.Depts orderby dept.no select dept;
        return data.ToList();
    }

    // GET api/values/5
    public Dept Get(int id)
    {
        AndroidAppDBEntities db = new AndroidAppDBEntities();
        var data = from dept in db.Depts where dept.no == id select dept;
        return data.SingleOrDefault();
    }

    // POST api/values
    public void Post(Dept obj)
    {
        AndroidAppDBEntities db = new AndroidAppDBEntities();
        db.Depts.Add(obj);
        db.SaveChanges();
    }

    // PUT api/values/5
    public void Put(int id,Dept obj)
    {
        AndroidAppDBEntities db = new AndroidAppDBEntities();
        var data = from dept in db.Depts where dept.no == id select dept;
        Dept old = data.SingleOrDefault();
        old.no = obj.no;
        old.name = obj.name;
        db.SaveChanges();
    }

    // DELETE api/values/5
    public void Delete(int id)
    {
        AndroidAppDBEntities db = new AndroidAppDBEntities();
        var data = from dept in db.Depts where dept.no == id select dept;
        Dept obj = data.SingleOrDefault();
        db.Depts.Remove(obj);
        db.SaveChanges();

    }
 }
}


Global.asax.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

 namespace MvcAppDept
{


public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();


    }
   }

}

MainActivity.cs

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace DeptAndroidApp
{
    [Activity(Label = "DeptAndroidApp", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {


        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);
            Button GetButton = FindViewById<Button>(Resource.Id.GetButton);
            var txtValue1 = FindViewById<EditText>(Resource.Id.txtValue1);
            int id = Convert.ToInt32(txtValue1.Text);
            var No = FindViewById<TextView>(Resource.Id.No);
            var Name = FindViewById<TextView>(Resource.Id.Name);
            //GetButton.Click += GetDept(id); 
            GetButton.Click+=async(sender,args)=>{
           //error  Cannot await 'DeptAndroidApp.dept                  
           Dept dept=await GetDept(id);
                No.Text=dept.No;
                Name.Text=dept.name}
        }
        //Error The return type ofasync method must be void,task orTask<T>
        public async Dept GetDept(int id)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://****.***/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new               System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                var result= await client.GetAsync(string.Format("/api/dept/{0}",id));
               return JsonConvert.DeserializeObject<Dept>(await result.Content.ReadAsStringAsync());                }       
        }

    }
}

1 个答案:

答案 0 :(得分:5)

以下是我将如何从任何项目(包括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));
     }
}

无论如何,这应该让你开始朝着正确的方向前进。这绝对可以清理干净,而且我是徒手写的,所以可能会有一些拼写错误。

更新

更新您的MainActivity.cs

而不是int id = Convert.ToInt32(txtValue1)

使用

int id = Convert.ToInt32(txtValue1.Text);

而不是GetButton.Click += GetDept(id);

使用

GetButton.Click += async (sender, args) => {
   var dept = await GetDept(id);

   No.Text = dept.no;
   Name.Text = dept.name
}