将MessagePack与AspNet Core WebAPI和Console App一起使用

时间:2018-04-26 06:56:14

标签: c# asp.net-core asp.net-core-webapi msgpack

我目前正在尝试在包含2个项目的解决方案中实现MessagePack:AspNet Core WebAPI和一个简单的控制台应用程序。添加了以下包:

如何在客户端反序列化对象,这里是代码片段,当从客户端向api发回一个对象时,我只是在客户端上序列化并将其发送到api中的Post方法,它将接受一个字符串,接受字符串并再次反序列化,我将需要以某种方式将类型传递给控制器​​。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MessagePack;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
{
   [Route("api/[controller]")]
   public class ValuesController : Controller
   {
     [HttpGet]
     public IActionResult Get()
     {
        var results = new List<Superhero>();

        results.Add(new Superhero { HeroID = 1, HeroName = "Bruce Wayne" });
        results.Add(new Superhero { HeroID = 2, HeroName = "Selina Kyle" });
        results.Add(new Superhero { HeroID = 3, HeroName = "Clark Kent" });

        var bytes = MessagePackSerializer.Serialize(results);

        return Ok(bytes);
    }

    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    [HttpPost]
    public void Post([FromBody]string value)
    {
        // how to I Deserialize here ? what do I just post from client to
        // with the Serialized object and pass the type also ???
    }

    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
   }

  [MessagePackObject]
  public class Superhero
  {
    [Key(0)]
    public int HeroID { get; set; }

    [Key(1)]
    public string HeroName { get; set; }
  }
}

          using MessagePack;
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Net.Http;
      using System.Text;
      using System.Threading.Tasks;

      namespace MessagePackExampleOne
      {
          class Program
          {
              static HttpClient client = new HttpClient();

              static void Main(string[] args)
              {
                  client.BaseAddress = new Uri("http://localhost:57752");
                  client.DefaultRequestHeaders.Accept.Clear();

                  HttpResponseMessage response = client.GetAsync("/api/values").Result;
                  if (response.IsSuccessStatusCode)
                  {
                      var result = response.Content.ReadAsStringAsync().Result;

                      //how to Deserialize this objec ??

                      // Console.WriteLine(MessagePackSerializer.ToJson(result));
                      // var mc2 = MessagePackSerializer.Deserialize<List<Superhero>>(result);
                  }

                  Console.Read();
              }


          }

          [MessagePackObject]
          public class Superhero
          {
              [Key(0)]
              public int HeroID { get; set; }

              [Key(1)]
              public string HeroName { get; set; }
          }
      }

0 个答案:

没有答案