简体   繁体   中英

Xamarin Android send Post data to WebApi

I have an Android app created with Xamarin in Visual Studio and I want to send a form data in json format to a Web Api created in C#. I tried a lot of methods from web an none worked.
Sometimes I get 500 Internal Server Error or sometimes I get null.
The last version I tried in WebApi is:

public HttpResponseMessage Post([FromBody]string value)      
{
    if (value == null || value == "") Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read subject/tutor from body");
    var user = JsonConvert.DeserializeObject<UsersModel>(value);
    dynamic json = System.Web.Helpers.Json.Decode(value);
    string newName = json.Name;
    string newSurname = json.Surname;
    string newUsername = json.Username;
    string newPassword = json.Password;

    string insertNewUser = "INSERT INTO USERS(NAME,SURNAME,USERNAME,PASSWORD) VALUES (:name,:surname,:username,:password) "; 
    using (OracleConnection conn = new OracleConnection(ConfigurationManager.ConnectionStrings["Licenta"].ConnectionString))
    {
        OracleCommand cmd = new OracleCommand(insertNewUser, conn);
        cmd.Parameters.Add("name", newName);
        cmd.Parameters.Add("surname", newSurname);
        cmd.Parameters.Add("username", newUsername);
        cmd.Parameters.Add("password", newPassword);
        cmd.ExecuteNonQuery();
    }

    return Request.CreateResponse(HttpStatusCode.OK);
}
catch(Exception ex)
{
    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}

The message I want to send to Web api is

{

    "name": "Ionescu",
    "surname": "Ralu",
    "username": "ralucuta",
    "password": "1235555",
    "usertype":1
}

This is my Xamarin Android app code:

public async Task<UserAccount> SaveProduct(UserAccount product)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://blabla:80/test/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        StringContent content = new StringContent(JsonConvert.SerializeObject(product), Encoding.UTF8, "application/json");
        // HTTP POST
        HttpResponseMessage response = await client.PostAsync("api/Users/", content);
        if (response.IsSuccessStatusCode)
        {
            string data = await response.Content.ReadAsStringAsync();
            product = JsonConvert.DeserializeObject<UserAccount>(data);
        }
    }
    return product;
}

public class UserAccount
{
    public string name { get; set; }
    public string surname { get; set; }
    public string username { get; set; }
    public string password { get; set; }
    public int usertype { get; set; }
}

Your rest api won't be called since you are passing UserAccount object and you are expecting string . change your web api signature like this

[HttpPost]
[Route("api/Users/save")]
public HttpResponseMessage MyMethod(UserAccount userAccount)      
{
 //your api code
}

And in your android code

public async Task<UserAccount> SaveProduct(UserAccount product)
{
    try { 
        using (var client = new HttpClient ()) {
            client.BaseAddress = new Uri ("http://blabla:80/test/");
            client.DefaultRequestHeaders.Accept.Clear ();
            client.DefaultRequestHeaders.Accept.Add (new MediaTypeWithQualityHeaderValue ("application/json"));
            var uri = new Uri ("http://blabla:80/test/api/Users/save");
            string serializedObject = JsonConvert.SerializeObject (product);
            HttpContent contentPost = new StringContent (serializedObject, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync (uri, contentPost);
            if (response.IsSuccessStatusCode) {
                var data = await response.Content.ReadAsStringAsync ();
                UserAccount product = JsonConvert.DeserializeObject<UserAccount>(data);
                return product;
            }
        }
    }
    catch (Exception) {
        return null;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM