gpt4 book ai didi

c# - 使用 HttpClient 将字节数组发布到 Web API 服务器

转载 作者:IT王子 更新时间:2023-10-29 04:18:42 24 4
gpt4 key购买 nike

我想将此数据发布到 Web API 服务器:

public sealed class SomePostRequest
{
public int Id { get; set; }
public byte[] Content { get; set; }
}

将此代码用于服务器:

[Route("Incoming")]
[ValidateModel]
public async Task<IHttpActionResult> PostIncomingData(SomePostRequest requestData)
{
// POST logic here
}

还有这个 - 对于客户:

var client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:25001/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));

var content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "id", "1" },
{ "content", "123" }
});

var result = await client.PostAsync("api/SomeData/Incoming", content);
result.EnsureSuccessStatusCode();

一切正常(至少,调试器在 PostIncomingData 中的断点处停止)。

因为有一个 byte 数组,我不想将它序列化为 JSON,而是想将它作为二进制数据发布以减少网络流量(类似于 application/octet-流).

如何实现?

我试过使用 MultipartFormDataContent,但看起来我就是无法理解,MultipartFormDataContent 将如何匹配 Controller 方法的签名。

例如,将内容替换为:

var content = new MultipartFormDataContent();
content.Add(new FormUrlEncodedContent(new Dictionary<string, string> { { "id", "1" } }));

var binaryContent = new ByteArrayContent(new byte[] { 1, 2, 3 });
binaryContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
content.Add(binaryContent, "content");

var result = await client.PostAsync("api/SomeData/Incoming", content);
result.EnsureSuccessStatusCode();

导致错误 415(“不支持的媒体类型”)。

最佳答案

WebAPI v2.1 及更高版本 supports BSON (Binary JSON) out of the box ,甚至还包含一个 MediaTypeFormatter。这意味着您可以以二进制格式发布整个消息。

如果你想使用它,你需要在WebApiConfig中设置它:

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Formatters.Add(new BsonMediaTypeFormatter());
}
}

现在,您可以在客户端使用相同的 BsonMediaTypeFormatter 来序列化您的请求:

public async Task SendRequestAsync()
{
var client = new HttpClient
{
BaseAddress = new Uri("http://www.yourserviceaddress.com");
};

// Set the Accept header for BSON.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/bson"));

var request = new SomePostRequest
{
Id = 20,
Content = new byte[] { 2, 5, 7, 10 }
};

// POST using the BSON formatter.
MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
var result = await client.PostAsync("api/SomeData/Incoming", request, bsonFormatter);

result.EnsureSuccessStatusCode();
}

或者,您可以使用 Json.NET 将您的类序列化为 BSON。然后,指定您要使用“application/bson”作为您的“Content-Type”:

public async Task SendRequestAsync()
{
using (var stream = new MemoryStream())
using (var bson = new BsonWriter(stream))
{
var jsonSerializer = new JsonSerializer();

var request = new SomePostRequest
{
Id = 20,
Content = new byte[] { 2, 5, 7, 10 }
};

jsonSerializer.Serialize(bson, request);

var client = new HttpClient
{
BaseAddress = new Uri("http://www.yourservicelocation.com")
};

client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/bson"));

var byteArrayContent = new ByteArrayContent(stream.ToArray());
byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/bson");

var result = await client.PostAsync(
"api/SomeData/Incoming", byteArrayContent);

result.EnsureSuccessStatusCode();
}
}

关于c# - 使用 HttpClient 将字节数组发布到 Web API 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32184360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com