发布自定义类型与HttpClient的 [英] Posting a Custom type with HttpClient

查看:203
本文介绍了发布自定义类型与HttpClient的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义DTO类:

I have a custom dto class:

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

和使用控制器的Web API(4.5 .NET框架)

and a Controller using Web Api (4.5 .net framework)

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

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

The client side only has 4.0 .net framework So I won't be able to use the PostAsJsonAsync() method. what is the solution to pass the object from my client to the server?

我曾尝试somethinig这样的:

I have tried somethinig like the following:

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

但它引发了我的异常:

however it throws me the 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库?

Isn't it possible to use the Newtonsoft.Json library?

推荐答案

当然。只是自己创建这样一个新的HttpContent类...

Sure. Just create yourself a new HttpContent class like this...

  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;
        }
    }

,现在你可以把你的对象为JSON就这样

and now you can send your object as Json just like this

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

这篇关于发布自定义类型与HttpClient的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆