使用HttpClient发布自定义类型

时间:2013-12-10 11:26:02

标签: c# asp.net-web-api dotnet-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<myObject>(objectTest)).Result;

然而它引发了我的异常:

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库?

2 个答案:

答案 0 :(得分: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;
        }
    }

现在您可以将您的对象发送为Json,就像这样

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

答案 1 :(得分:0)

创建一个继承自HttpContent的类,该类为您提供网络流,您可以直接对其进行写入,而无需使用memoryStream

类似这样的东西:

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Http.Helper.Extensions
{
    public class JsonHttpContentSerializer : HttpContent
    {

        private object Value { get; set; }

        public JsonHttpContentSerializer(Object value)
        {
            this.Value = value;
        }


        protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            using (var streamWriter = new StreamWriter(stream, new UTF8Encoding(false), 1024, true))
            {
                using (var jsonTextWriter = new JsonTextWriter(streamWriter) { Formatting = Formatting.None })
                {
                    var jsonSerializer = new JsonSerializer();
                    jsonSerializer.Serialize(jsonTextWriter, Value);
                    jsonTextWriter.Flush();
                }
            }

        }

        protected override bool TryComputeLength(out long length)
        {
            length = -1;
            return false;
        }

    }
}

,您会喜欢使用

var jsonSerializeContent = new JsonHttpContentSerializer(someContent);
httpRequestMessage.Content = jsonSerializeContent;