使用HttpClient发布自定义类型

我有一个自定义的dto类:

public class myObject { public string Id { get; set; } public string Name { get; set; } } 

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

 [HttpPost] public IHttpActionResult StripArchiveMailboxPermissions(myObject param) { DoSomething(param); return OK(); } 

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

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

 var response = Client.SendAsync(new HttpRequestMessage(objectTest)).Result; 

但它抛出了我的exception:

 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. 

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

当然。 只需像这样创建一个新的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(); tcs.SetResult(null); return tcs.Task; } protected override bool TryComputeLength(out long length) { length = _Stream.Length; return true; } } 

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

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