如何在 xamarin CrossPlatform 应用程序中使用 Web Api [英] How to Consume Web Api in xamarin CrossPlatform Application

查看:24
本文介绍了如何在 xamarin CrossPlatform 应用程序中使用 Web Api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这里是 web api

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

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

    }
}

推荐答案

以下是我在几乎任何项目(包括 Xamarin 项目)中使用此服务的方式.

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

首先,去掉 Global.asax 文件中的一行:

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

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

一般来说,这是不好的做法.您希望至少有可用的 XML 和 JSON 格式化程序,因为在宁静的环境中,由消费者决定他们需要/想要什么类型的序列化.

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.

接下来,我将使用 System.Net.Http.HttpClient 类与此服务交互.

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

从这一点开始与 Web Api 服务交互相当简单.以下是一些示例.

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.

更新

更新您的 MainActivity.cs

Update your 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
}

这篇关于如何在 xamarin CrossPlatform 应用程序中使用 Web Api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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