使用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
现在你可以像Json一样发送你的对象了
var content = new JsonContent(new YourObject()); var httpClient = new HttpClient(); var response = httpClient.PostAsync("http://example.org/somewhere", content);
- 在Web.API控制器中自动反序列化为类似字符串的类
- WebApi,Autofac,System.Web.Http.Filters.ActionFilterAttribute每个请求的实例
- ASP.NET Web API中的多个PUT方法
- 反序列化为double时,JsonConvert会抛出一个“非有效整数”exception
- 在ASP.Net Web Api 2中使用PUT动词上传文件
- WebApi自定义filter与构造函数中的注入接口不会被调用
- 使用AttributeRouting在WebAPI中指定默认控制器/操作路由
- ASP.NET Web API中的可选查询字符串参数
- 如何在HttpClient response.ReasonPhrase中获取真正的错误消息?