xamarin for android webservice

首先新建一个空网站,添加一个webservice服务。然后在UserWebService.cs类里编写对外服务的方法

[WebMethod]
public string IsCorret(string  userName , string userPassWord) {
    if (userName.Equals("cjx") && userPassWord.Equals("123"))
    {
        return "True";
    }
    else
    {
        return "False";
    }   
}


在浏览器中运行下,判断服务是否可以正常使用。确保可以正常使用后,在xamarin项目中WebReferences文件夹项右击添加Web引用

 

在Activity类里编写如下代码,下面主要是在一个button事件中添加对webservice的调用

TextView tvUser = null;
TextView tvPassWord = null;
protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView(Resource.Layout.Login);

    Button button = FindViewById<Button>(Resource.Id.into);
    button.Click += (sender, e) => {
        UserService.UserWebService us = new UserService.UserWebService();
        //webservice调用完成后触发
        us.IsCorretCompleted += new UserService.IsCorretCompletedEventHandler(us_IsCorretCompleted);

        tvUser = FindViewById<TextView>(Resource.Id.accountNumber1);
        tvPassWord = FindViewById<TextView>(Resource.Id.password);
        us.IsCorretAsync(tvUser.Text, tvPassWord.Text);
    };          
}

当webservice方法执行完成的时候会触发如下事件

void us_IsCorretCompleted(object sender, UserService.IsCorretCompletedEventArgs e)
{
    if (e.Result.Equals("True"))
    {
        //设置一个意图
        var intent = new Intent(this, typeof(MainActivity));
        StartActivity(intent);
    }
    else {
        Toast.MakeText(this, "登录失败!", ToastLength.Short).Show();
    }
}


不过这样子还是会出错的,这里要感谢这篇文章的博主!

http://www.codeproject.com/Articles/641570/MonoAndroid-Using-dotnet-webservice-ASMX

通过这里的讲解因为该项目是在android模拟器下运行的本地地址而是windows上的地址。于是不能使用localhost,而是要使用10.0.2.2

10.0.2.2 (Special alias to your host loopback interface (i.e., 127.0.0.1 on your development machine))

于是打开自动生产的类,修改下ip地址为10.0.2.2即可

原文地址:https://www.cnblogs.com/chenjianxiang/p/3788979.html