1

这是我在此页面上的第一个问题。我在 mvc webapi 和 Windows Store 应用程序中有应用程序,我想用 W8 应用程序向 web api 请求我的对象:

我的对象:

 var objobj = new ObjectCompleteAdd()
            {
                NameObject = "Name",
                DescriptionObject = "Description",
                isActveObject = true,
                ContractStartObject = DateTime.Parse("2005-09-01"),
                CityAdress = " CityAdress",
                PostCodeAdress = "PostCode",
}

BLL 中的类:

 public class ObjectCompleteAdd
    {  
        public string NameObject { get; set; }
        public string DescriptionObject { get; set; }
        public bool? isActveObject { get; set; }
        public DateTime ContractStartObject { get; set; }
        public string CityAdress { get; set; }
        public string PostCodeAdress { get; set; }
}

和我的功能:

  var dataContractSerializer = new DataContractJsonSerializer(typeof(ObjectCompleteAdd));
            var memoryStream = new MemoryStream();
            dataContractSerializer.WriteObject(memoryStream, objobj);
            HttpContent content = new StreamContent(memoryStream);  

            await client.PostAsync("api/ObjectISApi",content);

在 webapi 我有帖子:

  // POST api/ObjectISApi    
        public HttpResponseMessage PostObjectIS(ObjectCompleteAdd obj)
        {     
            ObjectIS.AddNewObject(obj);
            return Request.CreateResponse(HttpStatusCode.OK);

        }

它不起作用

4

1 回答 1

0

序列化对象后,倒回流,将位置设置为零:

var dataContractSerializer = new DataContractJsonSerializer(typeof(ObjectCompleteAdd));
var memoryStream = new MemoryStream();
dataContractSerializer.WriteObject(memoryStream, objobj);

// Rewind stream.
memoryStream.Position = 0;

HttpContent content = new StreamContent(memoryStream);

更新:好吧,我认为您还需要修改服务器代码,以正确反序列化您发送的 JSON 对象。ASP.NET 不会自动反序列化 JSON。

public ActionResult PostObjectIS()
{
    StreamReader reader = new StreamReader(Request.InputStream);
    string contentString = reader.ReadToEnd();

    JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
    var oca = jsonSerializer.Deserialize<ObjectCompleteAdd>(contentString);
    Debug.WriteLine(oca.NameObject);

    return View();
}
于 2013-01-23T00:39:34.077 回答