为了将数据发送到服务器,我使用此解决方案:
https://stackoverflow.com/a/19664927/8033752
但是如何通过POST将数据发送到concret端点RESTful?
答案 0 :(得分:1)
这是我的工作方式 - 对PATCH
的工作方式类似。下面的代码经过优化,只有有限的注释和异常处理来证明原理。
该示例是一个通用的异步方法,因此它可以接受任何可序列化的内容,包括单个和多个文件流:
/// <summary>
/// Calls a JSON/REST POST service.
/// </summary>
/// <typeparam name="TValue">Type of to be sent value.</typeparam>
/// <param name="loadPackage">Mandatory. The package the post call shall carry.</param>
/// <param name="requestUri">Mandatory. URI which shall be called.</param>
/// <returns>Returns the plain service response.</returns>
public async Task<HttpResponseMessage> CallPostServicePlainAsync<TValue>(
TValue loadPackage,
string requestUri)
{
using (var httpClient = CreateHttpClient()) // or just `new HttpClient()` plus magic
{
bool isStream = typeof(TValue) == typeof(Stream);
bool isMultipleStreams = typeof(TValue) == typeof(Stream[]);
if (isStream || isMultipleStreams)
{
var message = new HttpRequestMessage();
message.Method = HttpMethod.Post; // that's what makes it a POST :-)
var content = new MultipartFormDataContent();
if (isStream) // single stream
content.Add(new StreamContent(loadPackage as Stream));
else if (isMultipleStreams) // this is an array of streams
foreach (Stream stream in loadPackage as Stream[])
content.Add(new StreamContent(stream));
else // oops
throw new NotImplementedException("incorrect load package.");
message.Content = content;
message.RequestUri = new Uri(requestUri);
return await httpClient.SendAsync(message).ConfigureAwait(false);
} else {
// standard serializable content (not streams)
...
}
}
}