Windows Phone 7 访问 Azure 移动服务(远程服务器返回错误:未找到)
-
13-12-2019 - |
题
我尝试从Azure创建新的移动服务,并且JSON正确曝光了数据。
https://lifehope.azure-mobile.net/tables/USERPF
USERPF 是一个示例表。
为了简化问题,我只是将权限修改为“所有人”。
问题是下面列出的代码不起作用。错误信息是: 远程服务器返回错误:未找到当我点击“插入”按钮在 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;
}
}
解决方案
您正在发送 JSON 数据,但您说它具有不同的内容类型:
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
在请求中设置正确的内容类型:
wc.Headers["Content-Type"] = "application/json";
一些不相关的事情:如果你的类型没有装饰 [DataContract]
, ,您不需要用以下方式修饰属性 Column1 和 Column2 [DataMember]
.
其他提示
尝试投射 arg.Erro
r 至 WebException
, ,并检查状态代码。可能是 401(未经授权)
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
}
不隶属于 StackOverflow