Xamarin Android将发布数据发送到WebApi

时间:2017-06-04 20:19:03

标签: c# android json asp.net-web-api xamarin

我在 Visual Studio 中使用 Xamarin 创建了一个Android应用,我想将json格式的表单数据发送到 Web Api 在C#中创建。我从网上尝试了很多方法,没有工作 有时我得到500内部服务器错误或有时我得到null 我在WebApi中尝试的最后一个版本是:

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);
}
}

我要发送给Web API的消息是

{

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

这是我的Xamarin Android应用代码:

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; }
}

1 个答案:

答案 0 :(得分:0)

由于您传递的是UserAccount对象并且您期待string,因此不会调用您的其余api。像这样改变你的web api签名

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

并在您的Android代码中

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;
    }
}