我已经在xamarin.forms中创建了简单的登录页面,我有这些登录的API,而在postman运行时获取输出,但是从模拟器登录时,我收到以下错误。
{StatusCode:404,ReasonPhrase:' Not Found',Version:1.1,Content:System.Net.Http.StreamContent,Headers: { 缓存控制:私有 服务器:Microsoft-IIS / 8.0 X-AspNet-Version:4.0.30319 X-Powered-By:ASP.NET Set-Cookie:ARRAffinity = 639506ba4afdd530b4429c0d57e89977accb4b666a1e17dbe3fcc5c1fce369d5; Path = /; HttpOnly; Domain = snovahub.azurewebsites.net 日期:2017年9月13日星期三13:23:00 GMT 内容长度:3485 内容类型:text / html;字符集= utf-8的 }}
我的Api方法如下:
#region Get results from api
public static async Task<T> GetResultFromApi<T>(string serviceUrl,bool isTrue=true)
{
try
{
GetConnection();
var response = await _httpClient.GetAsync(new Uri(SnovaHubApiUrls.SnovaHubWebUrl + serviceUrl));
var stringAsync = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var responseJson = stringAsync;
return JsonConvert.DeserializeObject<T>(responseJson);
}
LoggingManager.Error("Received error response: " + stringAsync);
return default(T);
}
catch (Exception exception)
{
LoggingManager.Error(exception);
return default(T);
}
}
#endregion
答案 0 :(得分:1)
问题是您正在设置HttpClient.BaseAddress
,然后在调用HttpClient.GetAsync()
时传入完整的网址。你需要选择其中一个。所以:
选项1:
private static void GetConnection() {
if (_httpClient == null) {
_httpClient = new HttpClient { BaseAddress = new Uri(SnovaHubApiUrls.SnovaHubWebUrl) }; //You MUST place a / (slash) at the end of your BaseAddress ("http://something.com/api/" for example)
}
}
然后在您的GetResultFromApi()
方法中:
...
var response = await _httpClient.GetAsync(serviceUrl); //You MUST NOT place a slash at the beginning of 'serviceUrl' when using BaseAddress
选项2:
private static void GetConnection() {
if (_httpClient == null) {
_httpClient = new HttpClient(); //Removed BaseAddress
}
}
然后在您的GetResultFromApi()
方法中:
...
var response = await _httpClient.GetAsync(new Uri(SnovaHubApiUrls.SnovaHubWebUrl + serviceUrl)); //Passing full URL