【发布时间】:2017-05-14 22:04:26
【问题描述】:
我的 Xamarin PCL 项目中有这段代码。但是,在要调用 GetStringAsync 方法的第 4 行,代码在该点退出该方法并且不返回任何响应。我无法从 Web 服务获取 json 数据,并且尝试了几种解决方法但均未成功。我正在使用 Visual Studio 2015。
//this calls the webservice
public class RestClient<T>
{
private const string WebServiceUrl = "http://localhost:14241/api/Employees/";
public async Task<List<T>> GetAsync()
{
var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync(WebServiceUrl);
var taskModels = JsonConvert.DeserializeObject<List<T>>(json);
return taskModels;
}
public async Task<bool> PostAsync(T t)
{
var httpClient = new HttpClient();
var json = JsonConvert.SerializeObject(t);
HttpContent httpContent = new StringContent(json);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = await httpClient.PostAsync(WebServiceUrl, httpContent);
return result.IsSuccessStatusCode;
}
public async Task<bool> PutAsync(int id, T t)
{
var httpClient = new HttpClient();
var json = JsonConvert.SerializeObject(t);
HttpContent httpContent = new StringContent(json);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = await httpClient.PutAsync(WebServiceUrl + id, httpContent);
return result.IsSuccessStatusCode;
}
public async Task<bool> DeleteAsync(int id, T t)
{
var httpClient = new HttpClient();
var response = await httpClient.DeleteAsync(WebServiceUrl + id);
return response.IsSuccessStatusCode;
}
}
//this is the main view model that binds to the XAML page
public class MainViewModel : INotifyPropertyChanged
{
private List<Employee> _employeeList;
public List<Employee> EmployeesList
{
get { return _employeeList; }
set
{
_employeeList = value;
OnPropertyChanged();
}
}
public MainViewModel()
{
InitializeDataAsync();
}
private async Task InitializeDataAsync()
{
var employeeServices = new EmployeesServices();
EmployeesList = await employeeServices.GetEmployeesAsync();
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName=null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
//method that calls the GetAsync() method to retrieve the employee list
//from the web service
public class EmployeesServices
{
public async Task<List<Employee>> GetEmployeesAsync()
{
RestClient<Employee> restClient = new RestClient<Employee>();
var employeesList = await restClient.GetAsync();
return employeesList;
}
}
【问题讨论】:
-
最好的办法是运行一个通信跟踪(wireshark)来查看网络层发生了什么。但在你这样做之前......只需打开 WebServiceUrl 的浏览器,看看你是否得到响应。按 F12 键并观察数据包。
-
你是怎么调用这个方法的?您只是从应用程序
main中调用GetAsync()吗?你有minimal/complete/verifiable example that could show us this problem吗? -
感谢@John,我已经测试了 Web 服务 url,它按预期工作。它实际上在其他应用程序中使用。
-
@birryree,我从使用 MVVM 方法填充我的视图的服务类调用此方法。下面是来自服务类的方法调用示例
-
@ObinnaOsuji 我将您的
WebServiceUrl替换为新的json_test_link,它返回正确的响应。所以问题发生在网络层。
标签: c# xamarin visual-studio-2015 xamarin.android xamarin.forms