如何使用WebApi在Windows Phone 8.1上获取列表

时间:2016-01-12 17:12:03

标签: c# windows-phone-8.1

如何根据我的Web API代码使用Windows Phone进行GET?发帖子我已经知道并为我工作,但我不知道从我的API中检索收藏列表,谢谢!

我的API代码:

public class UsersController : ApiController
{
    private ApiDatabaseEntities data = new ApiDatabaseEntities();

    public IHttpActionResult GetUsuarios()
    {           
        try
        {
            IEnumerable<Usuario> usuarios = data.Usuario.AsEnumerable();
            return Ok(usuarios.AsEnumerable());
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        } 
    }
    public IHttpActionResult PostUsuarios(Usuario usuario)
    {
        try
        {
            data.Usuario.Add(usuario);
            data.SaveChanges();
            return Ok();
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }

这是我的Windows手机代码:

1 - WebApiBase

public abstract class WebApiBase<T>
{
    private string Url = "http://localhost:63964/api/users";

    protected virtual void Post(object objectPost)
    {
        HttpClient client = new HttpClient();
        client.PostAsJsonAsync(Url, objectPost);
    }     
    public abstract void Send(T objectPost);

}

2 - 和UsuarioApi

public class UsuarioApi : WebApiBase<Models.UserPhone>
{
    public override void Send(UserPhone objectPost)
    {
        this.Post(objectPost);
    }
}

1 个答案:

答案 0 :(得分:0)

用于从Windows Phone向服务器发送get请求,然后处理来自服务器的响应。

public async void GetRequest(){                string url = "APIurl";
                HttpClient _client = new HttpClient();
                HttpResponseMessage _response = await _client.GetAsync(new Uri(url));
                if (_response.IsSuccessStatusCode)
                {
                    string APIResponse = await _response.Content.ReadAsStringAsync();
                    var myObject = Newtonsoft.Json.Linq.JArray.Parse(APIResponse).ToObject<MyClass>();
                }
}

和MyClass

public class MyClass
{
public ObservableCollection<CollectionClass> _myCollection{get;set;}
}

public class CollectionClass
{
public string Name{get;set;}
}

现在您可以根据需要对myObject执行操作。