【问题标题】:xamarin form not calling web api using visual studio 2015xamarin 表单不使用 Visual Studio 2015 调用 Web api
【发布时间】:2018-05-24 15:17:37
【问题描述】:

我想通过 Xamarin 表单调用 web api(在我本地的视觉工作室上) 但它没有调用我的 web api。我正在使用 Visual Studio 安卓模拟器。

我正在使用 Visual Studio 2015 更新 3,这是我的代码

 public class DataService
{

    HttpClient client = new HttpClient();
    string apiPaht = "http://10.0.2.2:19367/api/";
    //string apiPaht = "http://localhost:19367/api/";

    public async Task<List<CustomerApp>> GetTodoItemsAsync()
    {
        var response = await client.GetStringAsync(apiPaht+ "APICustAccount/getTestData");
        var todoItems = JsonConvert.DeserializeObject<List<CustomerApp>>(response);
        return todoItems;
    }

}

我的 xamal.cs 上的代码

  async void RefreshData()
    {
        List<CustomerApp> listCust = await _dService.GetTodoItemsAsync();           
        todoList.ItemsSource = listCust;
        string aa = "";
    }

   protected void btn_click(object sender, EventArgs e)
    { 
      RefreshData();
    }

【问题讨论】:

  • 您的应用程序是否有互联网权限?一世。 e. AndroidManifest.xml 中的&lt;uses-permission android:name="android.permission.INTERNET" /&gt;
  • 你能从模拟器浏览器访问那个 URL 吗?
  • 是的,我有互联网权限@tamas Szabo
  • 您可以通过浏览器访问 API(无论是从模拟器还是从您的 PC)?
  • 我是移动开发新手,我不知道使用模拟器浏览器。请告诉我使用模拟器浏览器

标签: c# xamarin xamarin.android xamarin.forms


【解决方案1】:

您好,请尝试以下代码,如果您有任何疑问,请告诉我。

获取方法:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://10.0.2.2:19367/api/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("APICustAccount/getTestData").Result;
if (response.StatusCode == HttpStatusCode.OK)
{
    var result = await response.Content.ReadAsStringAsync();
    var todoItems = JsonConvert.DeserializeObject<List<CustomerApp>>(result);
}

我已经测试了上面的代码,它对我有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多