使用HttpClient发布自定义类型

use*_*666 1 c# asp.net-web-api dotnet-httpclient

我有一个自定义的dto类:

public class myObject
{
    public string Id { get; set; }
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

和使用Web Api的控制器(4.5 .net框架)

[HttpPost]
public IHttpActionResult StripArchiveMailboxPermissions(myObject param)
{
    DoSomething(param);
    return OK();
}
Run Code Online (Sandbox Code Playgroud)

客户端只有4.0 .net框架所以我将无法使用PostAsJsonAsync()方法.将对象从我的客户端传递到服务器的解决方案是什么?

我试过像下面这样的东西:

var response = Client.SendAsync(new HttpRequestMessage<myObject>(objectTest)).Result;
Run Code Online (Sandbox Code Playgroud)

但它抛出了我的异常:

Could not load file or assembly 'Microsoft.Json, Version=2.0.0.0, 
Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. 
The system cannot find the file specified.
Run Code Online (Sandbox Code Playgroud)

是不是可以使用Newtonsoft.Json库?

Dar*_*ler 6

当然.只需像这样创建一个新的HttpContent类......

  public class JsonContent : HttpContent
    {

        private readonly MemoryStream _Stream = new MemoryStream();

        public JsonContent(object value)
        {

            var jw = new JsonTextWriter(new StreamWriter(_Stream)) {Formatting = Formatting.Indented};
            var serializer = new JsonSerializer();
            serializer.Serialize(jw, value);
            jw.Flush();
            _Stream.Position = 0;

        }
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            _Stream.CopyTo(stream);
            var tcs = new TaskCompletionSource<object>();
            tcs.SetResult(null);
            return tcs.Task;
        }

        protected override bool TryComputeLength(out long length)
        {
            length = _Stream.Length;
            return true;
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在你可以像Json一样发送你的对象了

  var content = new JsonContent(new YourObject());
  var httpClient = new HttpClient();
  var response = httpClient.PostAsync("http://example.org/somewhere", content);
Run Code Online (Sandbox Code Playgroud)