如何消耗xamarin跨平台应用程序Web阿比 [英] How to Consume Web Api in xamarin CrossPlatform Application

查看:375
本文介绍了如何消耗xamarin跨平台应用程序Web阿比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建的Web API从SQL数据库检索数据。我需要使用Web API中xamrin Android和xamarin为iOS。截至目前xamarin为Android。我不知道如何调用GET和POST方法的基础上的按钮单击事件。

下面是网络API

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Net;
使用System.Net.Http;
使用System.Web.Http;

命名空间MvcAppDept.Controllers
{
公共类DeptController:ApiController
{
    //获取API /值
    公开的IEnumerable<部>得到()
    {
        AndroidAppDBEntities DB =新AndroidAppDBEntities();
        VAR数据部门在db.Depts =排序依据dept.no选择部门;
        返回data.ToList();
    }

    //获取API /价值/ 5
    公共部门获取(INT ID)
    {
        AndroidAppDBEntities DB =新AndroidAppDBEntities();
        VAR数据=从部门在db.Depts那里dept.no == ID选择部门;
        返回data.SingleOrDefault();
    }

    // POST API /值
    公共无效后(部OBJ)
    {
        AndroidAppDBEntities DB =新AndroidAppDBEntities();
        db.Depts.Add(OBJ);
        db.SaveChanges();
    }

    // PUT API /价值/ 5
    公共无效认沽(INT ID,部门OBJ)
    {
        AndroidAppDBEntities DB =新AndroidAppDBEntities();
        VAR数据=从部门在db.Depts那里dept.no == ID选择部门;
        部旧= data.SingleOrDefault();
        old.no = obj.no;
        old.name = obj.name;
        db.SaveChanges();
    }

    //删除API /价值/ 5
    公共无效删除(INT ID)
    {
        AndroidAppDBEntities DB =新AndroidAppDBEntities();
        VAR数据=从部门在db.Depts那里dept.no == ID选择部门;
        部OBJ = data.SingleOrDefault();
        db.Depts.Remove(OBJ);
        db.SaveChanges();

    }
 }
}


的Global.asax.cs

使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用的System.Web;
使用System.Web.Http;
使用System.Web.Mvc;
使用System.Web.Optimization;
使用System.Web.Routing;

 命名空间MvcAppDept
{


公共类WebApiApplication:System.Web.HttpApplication
{
    保护无效的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

 使用系统;
使用System.Net.Http;
使用System.Threading.Tasks;
使用Android.App;
使用Android.Content;
使用Android.Runtime;
使用Android.Views;
使用Android.Widget;
使用Android.OS;
命名空间DeptAndroidApp
{
    [活动(标签=DeptAndroidApp,MainLauncher = TRUE,图标=@可绘制/图标)]
    公共类MainActivity:活动
    {


        保护覆盖无效的OnCreate(束捆)
        {
            base.OnCreate(包);
            的setContentView(Resource.Layout.Main);
            按钮GetButton = FindViewById<按钮>(Resource.Id.GetButton);
            VAR txtValue1 = FindViewById<的EditText>(Resource.Id.txtValue1);
            INT ID = Convert.ToInt32(txtValue1.Text);
            无功无= FindViewById< TextView的>(Resource.Id.No);
            VAR名称= FindViewById< TextView的>(Resource.Id.Name);
            //GetButton.Click + = GetDept(ID);
            GetButton.Click + =异步(发件人,参数)=> {
           //错误不能等待DeptAndroidApp.dept
           部部=等待GetDept(ID);
                No.Text = dept.No;
                Name.Text = dept.name}
        }
        //错误的返回类型ofasync方法必须是无效的,任务orTask< T>
        公共异步部门GetDept(INT ID)
        {
            使用(VAR的客户=新的HttpClient())
            {
                client.BaseAddress =新的URI(HTTP://****.***/);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(新System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(应用/ JSON));
                VAR的结果=等待client.GetAsync(的String.Format(/ API /部门/ {0},ID));
               返回JsonConvert.DeserializeObject<部>(等待result.Content.ReadAsStringAsync()); }
        }

    }
}
 

解决方案

下面是我会怎么使用这项服务从几乎任何项目(包括Xamarin项目)。

首先,摆脱线在Global.asax文件,上面写着这样的:

  GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
 

一般来说,这是不好的做法。你想拥有至少XML和JSON格式化用,因为在一个宁静的环境,它是由消费者来决定他们需要什么类型的系列化/想要的。

接下来,我会使用 System.Net.Http.HttpClient 类与这个服务进行交互。

从这个点上的Web API服务的交互是相当简单的。下面是一些例子。

 公共异步名单,其中,部> GetDepts()
{
     使用(VAR的客户=新的HttpClient())
     {
          client.BaseAddress =新的URI(HTTP://< ip地址:端口> /);
          client.DefaultRequestHeaders.Accept.Clear();
          client.DefaultRequestHeaders.Accept.Add(新MediaTypeWithQualityHeaderValue(应用/ JSON));

          返回等待client.GetAsync(/ API /部门);
     }
}

公共异步任务<部> GetDept(INT ID)
{
     使用(VAR的客户=新的HttpClient())
     {
          client.BaseAddress =新的URI(HTTP://< ip地址:端口> /);
          client.DefaultRequestHeaders.Accept.Clear();
          client.DefaultRequestHeaders.Accept.Add(新MediaTypeWithQualityHeaderValue(应用/ JSON));

          VAR的结果=等待client.GetAsync(的String.Format(/ API /部门/ {0},ID));

          返回JsonConvert.DeserializeObject<部>(等待result.Content.ReadAsStringAsync());
     }
}

公共异步任务AddDept(系部)
{
     使用(VAR的客户=新的HttpClient())
     {
          client.BaseAddress =新的URI(HTTP://< ip地址:端口> /);

          等待client.PostAsJsonAsync(/ API /部门,部门);
     }
}

公共异步任务UpdateDept(系部)
{
     使用(VAR的客户=新的HttpClient())
     {
          client.BaseAddress =新的URI(HTTP://< ip地址:端口> /);

          等待client.PutAsJsonAsync(的String.Format(/ API /部门/ {0},dept.no),部门);
     }
}

公共异步任务DeleteDept(INT ID)
{
     使用(VAR的客户=新的HttpClient())
     {
          client.BaseAddress =新的URI(HTTP://< ip地址:端口> /);

          client.DeleteAsync(的String.Format(/ API /部门/ {0},ID));
     }
}
 

这应该让你在正确的方向开始呢。这肯定可以得到清理和我写的写意所以有可能会出现一些错别字。

更新

更新您的MainActivity.cs

而不是内部ID = Convert.ToInt32(txtValue1)

使用

 内部ID = Convert.ToInt32(txtValue1.Text);
 

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

使用

  GetButton.Click + =异步(发件人,参数)=> {
   VAR部门=等待GetDept(ID);

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

I have created web api that retrieves data from SQL database. I need to consume web api in xamrin for android and xamarin for iOS. as of now xamarin for android. I am not sure how to call GET and Post method based on button click event.

Here is 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());                }       
        }

    }
}

解决方案

Here is how I would use this service from just about any project (including Xamarin projects).

First, get rid of the line in your Global.asax file that says this:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

Generally speaking this is bad practice. You want to have at least the XML and JSON formatters available because in a restful environment it is up to the consumers to determine what type of serialization they need/want.

Next, I would use the System.Net.Http.HttpClient class to interact with this service.

Interacting with the Web Api service from this point is fairly straightforward. Here are some examples.

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));
     }
}

That should get you started in the right direction anyway. This could definitely get cleaned up and I wrote it freehand so there may be some typos.

Update

Update your MainActivity.cs

Instead of int id = Convert.ToInt32(txtValue1)

Use

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

Instead of GetButton.Click += GetDept(id);

Use

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

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

这篇关于如何消耗xamarin跨平台应用程序Web阿比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆