2017-06-04 56 views
0

我有XamarinVisual Studio中創建一個Android應用程序,我想以JSON格式發送表單數據在C#創建網絡API。我嘗試了很多來自網絡的方法,但都沒有成功。
有時我得到500內部服務器錯誤或有時我得到空。
的最後一個版本我的WebAPI嘗試是:Xamarin的Android發送POST數據的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

你測試了一些REST測試工具,像郵差網絡API,以驗證它與您的JSON數據? – Kenci

+0

我使用Chrome的Restlet客戶端擴展功能進行了測試,但沒有任何處理。我以爲我沒有正確接收和讀取數據 –

+1

你可以嘗試創建一個像這樣的控制器方法:https://stackoverflow.com/a/21579294/915414 - 只需使用UserAccount而不是PersonModel,然後用Restlet Client對其進行測試 – Kenci

回答

0

您的其他API將不會被調用,因爲您傳遞的是UserAccount對象,並且您期望string。改變這樣的

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

而在你的Android代碼的網頁API簽名

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