【发布时间】:2015-05-20 05:27:12
【问题描述】:
我目前正在学习 Xamarin 表单的不同解决方法。我创建了一个搜索天气信息并发送 HTTPResponseMessage 的 Web 服务。每次调用 API 时,我都会收到未找到的错误。
我在 API 上更改了路由,现在出现 JSON 解析错误:
public async Task<string> weather(){
var parameters = new Dictionary<string, string>{
{"lat", "33.92649137"}, {"lon", "-83.343567"}
};
try{
var xml = await MobileService.InvokeApiAsync<string>("GetWeather", HttpMethod.Get, parameters);
return xml;
}catch (Exception e){
DisplayAlert ("Error", e.ToString(), "Close");
return "Failed";
}
}
我的网络服务 api:
namespace MobileWeather.Controllers
{
public class TestController : TableController<Weather>
{
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
MobileServiceContext context = new MobileServiceContext();
DomainManager = new EntityDomainManager<Weather>(context, Request, Services);
}
public IQueryable<Weather> GetAllTodoItems()
{
return Query();
}
/// <summary>
/// Get the weather information for a location based on the longitude and latitude values.
/// </summary>
/// <param name="lat">The latitude of the project site.</param>
/// <param name="lon">The longitude of the project site.</param>
[HttpGet]
[Route("api/GetWeather")]
public async Task<HttpResponseMessage> GetWeather(string lon, string lat)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://forecast.weather.gov/MapClick.php");
string uri = "http://forecast.weather.gov/MapClick.php?lat=" + lat + "&lon=" + lon + "&FcstType=dwml";
//create a weather item.
Weather weather = new Weather();
HttpResponseMessage response = await client.GetAsync(uri);
XDocument xml = new XDocument();
xml = XDocument.Parse(await response.Content.ReadAsStringAsync(), LoadOptions.None);
/*
weather.Temperature = Convert.ToInt32( xml.Descendants("temperature").Descendants("value").ElementAt(0).Value);
weather.Lon = lon;
weather.Lat = lat;
weather.Precipitation = Convert.ToInt32(xml.Descendants("probability-of-precipitation").Descendants("value").ElementAt(0).Value);
weather.Forecast = xml.Descendants("wordedForecast").Descendants("text").ElementAt(0).Value;
weather.Hazard = xml.Descendants("hazards").Descendants("hazard-conditions").ElementAt(0).Value;
weather.DateAndTime = DateTime.Now;
*/
//query for the data we want!
return new HttpResponseMessage()
{
Content = response.Content
};
}
public HttpResponseMessage Post()
{
return new HttpResponseMessage()
{
Content = new StringContent("POST: Test message")
};
}
public HttpResponseMessage Put()
{
return new HttpResponseMessage()
{
Content = new StringContent("PUT: Test message")
};
}
}
}
更新 => 我将 GetWeather 方法上的路由更改为 [Route("api/GetWeather")],现在我遇到了解析错误。
【问题讨论】:
-
你能从浏览器调用你的服务吗?
-
是的,它在我的浏览器上运行良好...我将使用完整的 api 代码进行更新,看看是否有帮助。
标签: c# .net azure xamarin xamarin.forms