Windows Phone 7 access Azure Mobile Service (The remote server returned an error: not found)
-
13-12-2019 - |
Question
I try to create a new mobile service from Azure, and the data has been correctly exposed by Json.
https://lifehope.azure-mobile.net/tables/USERPF
USERPF is a sample table.
In order to simplify the question, I just modified the permission to "everyone".
The problems is the code listed below doesn't work. Error message is: the remote server returned an error: not found when I hit the Insert button to insert a new record in USERPF...
private void butInsert_Click(object sender, RoutedEventArgs e)
{
USERPF item = new USERPF();
item.Column1 = 789;
item.Column2 = 789;
WebClient wc = new WebClient();
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
//wc.Headers["X-ZUMO-APPLICATION"] = "";
wc.UploadStringCompleted += (ss, arg) =>
{
if (arg.Error == null)
{
MessageBox.Show("OK");
}
else
{
MessageBox.Show(arg.Error.Message);
}
};
wc.UploadStringAsync(
new Uri("https://lifehope.azure-mobile.net/tables/USERPF/"),
"POST", JsonHelper.ObjectToJson(item, typeof(USERPF)));
}
//USERPF.cs
public class USERPF
{
[System.Runtime.Serialization.IgnoreDataMember()]
public int id { get; set; }
[System.Runtime.Serialization.DataMember()]
public int Column1 { get; set; }
[System.Runtime.Serialization.DataMember()]
public int Column2 { get; set; }
}
//JsonHelper.cs
public static string ObjectToJson(object obj, Type type)
{
try
{
//Create a stream to serialize the object to.
MemoryStream ms = new MemoryStream();
// Serializer the User object to the stream.
DataContractJsonSerializer ser = new DataContractJsonSerializer(type);
ser.WriteObject(ms, obj);
byte[] json = ms.ToArray();
ms.Close();
return Encoding.UTF8.GetString(json, 0, json.Length);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return string.Empty;
}
}
Solution
You're sending JSON data, but you're saying that it's of a different content type:
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
Set the correct content-type in the request:
wc.Headers["Content-Type"] = "application/json";
Something unrelated: if your type isn't decorated with [DataContract]
, you don't need to decorate the properties Column1 and Column2 with [DataMember]
.
OTHER TIPS
Try to cast arg.Erro
r to WebException
, and check the Statuce code. It might be 401 (Unauthorized)
var webException = arg.Error as WebException;
if(webException == null) return;
if (webException.Response != null)
{
var response = (HttpWebResponse)webException.Response;
var status = response.StatusCode; //press F9 here
}