mshwf
mshwf

Reputation: 7469

Can't call a web api service from Xamarin forms?

I have this web api service:

 [HttpPost]
 public bool Post(UserModel newUser)
 {
    return regRepo.AddUser(newUser);
 }

I want to call it from Xamarin.Forms project, so I made this:

   private void AddUser(object obj)
    {
        var user = obj as UserModel;
        var url = @"http://localhost:57615/api/UsersApi/";
        var uri = new Uri(url);
        var client = new HttpClient();
        var json =  JsonConvert.SerializeObject(user);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        var response = client.PostAsync(uri, content);
     }

but it never call the service, I used Postman to make sure the URL is correct, and it works

EDIT

I changed the method signature to be async as klm_ suggested, but this error occurs:

the Application is in break mode

enter image description here

Upvotes: 0

Views: 963

Answers (2)

GeralexGR
GeralexGR

Reputation: 3592

Make sure obj is a correct instance of your model.

 try
 {
    HttpClient client = new HttpClient();
    var model = obj as UserModel ;
    var url = @"http://localhost:57615/api/UsersApi/";
    var json = JsonConvert.SerializeObject(model);
    HttpContent content = new StringContent(json);
    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    var response = await client.PostAsync(url, content);
    var message = await response.Content.ReadAsStringAsync();
    return message;
 }
 catch (Exception x)
 {
 // message
 }

Upvotes: 0

klm_
klm_

Reputation: 1209

Try this (add async and await)

private async void AddUser(object obj)
{
    var user = obj as UserModel;
    var url = @"http://localhost:57615/api/UsersApi/";
    var uri = new Uri(url);
    var client = new HttpClient();
    var json =  JsonConvert.SerializeObject(user);
    var content = new StringContent(json, Encoding.UTF8, "application/json");

    var response = await client.PostAsync(uri, content);
 }

Upvotes: 1

Related Questions