httpClient.PostAsync - Windows商店应用程序 - mvc webapi

时间:2013-01-22 22:59:11

标签: .net windows asp.net-mvc-4 windows-runtime

这是我在这个页面上的第一个问题。 我在mvc webapi和Windows应用商店应用程序中有应用程序,我想通过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);

        }

它不起作用

1 个答案:

答案 0 :(得分: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();
}