0

我尝试从 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;
        }
    }
4

2 回答 2

2

您正在发送 JSON 数据,但您说它是不同的内容类型:

wc.Headers["Content-Type"] = "application/x-www-form-urlencoded"; 

在请求中设置正确的内容类型:

wc.Headers["Content-Type"] = "application/json"; 

不相关的东西:如果你的类型没有用 装饰[DataContract],你不需要用 Column1 和 Column2 装饰属性[DataMember]

于 2012-10-04T03:30:49.860 回答
0

尝试将arg.Error 转换为WebException,并检查 Statuce 代码。可能是 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
   }
于 2012-10-03T10:59:27.637 回答