0

我的 Windows Phone 客户端发送了一段 JSON,表示名称和分数...我应该使用 Web API 中的类吗?将对象发送到服务器而不是原始 json 的代码是什么?

 private void btnCreateSampleScore_Click(object sender, RoutedEventArgs e)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://punkoutersoftware.azurewebsites.net");

            var content = new FormUrlEncodedContent(new[] 
                                                   {
                                                       new KeyValuePair<string, string>("Bob", "2.65")
                                                   });

            var result = client.PostAsync("/api/DrunkMeterScore", content).Result;

            string resultContent = result.Content.ReadAsStringAsync().Result;
            Console.WriteLine(resultContent);

            //DrunkMeterScore dms = new DrunkMeterScore();
            //dms.Name = "Bob";
            //dms.Score = 2.42;
        }

    }

服务器正在使用普通的 Web API 模板

 // POST api/DrunkMeterScore
    public HttpResponseMessage PostDrunkMeterScore(DrunkMeterScore drunkmeterscore)
    {
        if (ModelState.IsValid)
        {
            db.DrunkMeterScores.Add(drunkmeterscore);
            db.SaveChanges();

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, drunkmeterscore);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = drunkmeterscore.DrunkMeterScoreId }));
            return response;
        }
        else
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }
    }

编辑1:

我尝试了这两个..它们都挂起并且在 PostAsync 调用期间永远不会回来:(

 var client = new HttpClient();
        client.BaseAddress = new Uri("http://punkoutersoftware.azurewebsites.net");

        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

        var score = new DrunkMeterScore() { Name = "Joe", Score = 2.67 };






        //MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
        //HttpContent content = new ObjectContent<DrunkMeterScore>(score, jsonFormatter);
        //var resp = client.PostAsync("api/DrunkMeterScore", content).Result;






        //Uri scoreUri = null;
        //HttpResponseMessage response = client.PostAsJsonAsync("api/DrunkMeterScore", score).Result;
        //if (response.IsSuccessStatusCode)
        //{
        //    scoreUri = response.Headers.Location;
        //}
        //else
        //{
        //    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
        //}
4

1 回答 1

6

要序列化对象,您需要 ObjectContent 类,该类对于 wp8 仅作为 alpha 版本提供。

使用包控制台来做,

安装包 Microsoft.AspNet.WebApi.Client -Pre

应该是这样的。我是凭记忆做到的,所以 YMMV。

DrunkMeterScore dms = new DrunkMeterScore();
dms.Name = "Bob";
dms.Score = 2.42;
var content = new ObjectContent(dms, new JsonMediaTypeFormatter());

var result = client.PostAsync("/api/DrunkMeterScore", content).Result;
于 2013-06-18T22:31:07.677 回答