0
votes

I have a post method that sends json to my api.

My endpoint works in postman so my problem is in my xamarin post request:

    async void RegisterUser(object sender, System.EventArgs e)
    {
        string URL = "http://blablahblah:51001/register";

        HttpClient client = new HttpClient();

        var model = new RegisterViewModel
        {
            Email = EntryEmail.Text,
            FirstName = FirstName.Text,
            LastName = LastName.Text, 
            Password = EntryPasswrd.Text 

        };

        var content = JsonConvert.SerializeObject(model);

        await client.PostAsync(URL, new StringContent(content));

    }

after it hits the await client.PostAsync(URL, new StringContent(content)); line, the application just stops dead. no error messages or anything like that.

Any ideas?

EDIT:

My register method in my API solution:

    [Route("register")]
    [HttpPost]
    public async Task<ActionResult> InsertUser([FromBody] RegisterViewModel model)
    {
        var user = new IdentityUser
        {
            Email = model.Email,
            UserName = model.Email,
            SecurityStamp = Guid.NewGuid().ToString()
        };

        var result = await _userManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            var newUser = new User
            {
                Username = model.Email,
                FirstName = model.FirstName,
                LastName = model.LastName
            };

            _dbContext.Users.Add(newUser);
            await _dbContext.SaveChangesAsync();

        }
        return Ok(new { Username = user.UserName });
    }

and my view model i am passing the data through:

public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    [Required]
    public string Password { get; set; }
}

I have since rewrote my post method using the below suggestions, its still not returning any errors inside my catch block:

    public async Task<string> Registered(object details)
    {
        string URL = "http://blahblah:51001/register";

        HttpClient client = new HttpClient();

        var model = new RegisterViewModel
        {
            Email = EntryEmail.Text,
            FirstName = FirstName.Text,
            LastName = LastName.Text,
            Password = EntryPasswrd.Text

        };

        var content = JsonConvert.SerializeObject(model);

        try
        {
            await client.PostAsync(URL, new StringContent(content));
        }
        catch (Exception ex)
        {

            throw new Exception(ex.Message);
        }


        return "Registration Successful";
    }
2
are you sure that there are no connectivity issues? Can you reach your API url from the device's browser? Are you sure there are no exceptions or timesouts? Using async void is typically a bad idea - there are numerous posts and discussions about why this is and alternative approaches you should review. - Jason
Can you please add a try-catch block around the client.PostAsync to see if there is any exception? - Jack Hua
hi all, I have made the changes to my method, please check my edits above, thank you for your contributions! - dros
@Jason i ran the url in the android emulators browser and it doesnt seem to work? it says bad request? - dros

2 Answers

0
votes

Please test the Web Api with some REST testing tool like POSTMAN, to verify that it works with your JSON data firstly.

If your webapi have no problems, please take a look the following code, I can post data to asp.net core webapi successfully, and return value.

 private async void btnpost_Clicked(object sender, EventArgs e)
    {
        ContactModel cm = new ContactModel() {ID=1,Name="cherry",Age=12 };

        var httpClient = new HttpClient();
        var content = JsonConvert.SerializeObject(cm);
        HttpContent httpContent = new StringContent(content, Encoding.UTF8);
        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var uri = new Uri("http://xxx.xx.xx.xx:8088/api/Contact");
        HttpResponseMessage response = await httpClient.PostAsync(uri, httpContent);
        if (response.IsSuccessStatusCode)
        {
            var data = await response.Content.ReadAsStringAsync();

            string ss = data;
        }

    }

Please note: Adding android:usesCleartextTraffic="true" in Mainfeast.xml,because starting with Android 9 (API level 28), cleartext support is disabled by default. if not, you may have Cleartext HTTP traffic not permitted error.

0
votes

So after 2 days of googling i found a solution:

https://marketplace.visualstudio.com/items?itemName=vs-publisher-1448185.ConveyorbyKeyoti#overview

now I can post to my api from my xamarin forms project!!!

thanks for everyone's input