我正在尝试通过Xamarin.Forms应用程序使用.NET Web API。当我尝试调用get命令时,它会无限期地挂起并且永远不会返回内容。
using AspireITMobileSupport.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace AspireITMobileSupport
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Chat : ContentPage
{
private HttpClient _client;
public static ObservableCollection<Message> Messages { get; set; }
public Chat()
{
_client = new HttpClient();
InitializeComponent();
GetMessages().Wait();
}
private async Task GetMessages()
{
var response = await _client.GetAsync("[my site]/api/messages/1");
if (response.IsSuccessStatusCode)
var content = response.Content.ReadAsStringAsync().Result;
Messages = JsonConvert.DeserializeObject<ObservableCollection<Message>>(content);
}
}
}
}
和网络API:
using AspireITSupportAPI.Models;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
namespace AspireITSupportAPI.Controllers
{
public class MessagesController : ApiController
{
private ApplicationDbContext _context;
public MessagesController()
{
_context = new ApplicationDbContext();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
_context.Dispose();
}
// GET api/<controller>/5
public HttpResponseMessage Get(int id)
{
var messages = _context.Messages.Where(i => i.User == id).ToList<Message>();
return Request.CreateResponse(HttpStatusCode.OK, messages);
}
}
}
当我运行该应用程序时,它只是挂起然后崩溃。我知道GetMessages()。Wait();将同步运行。那不是问题。我只想获得结果,然后再专注于使一切异步。我已经使用Restlet Client测试了API,并且那里的一切似乎都正常运行。
我需要更改我的API中的内容还是我的Xamarin代码错误?