【发布时间】:2017-06-01 21:15:21
【问题描述】:
【问题讨论】:
-
你所说的“宁静”是什么意思? REST API 只是一个 HTTP 端点,REST 部分不会改变底层 HTTP 请求的语义。
【问题讨论】:
我就是这样做的——PATCH 的工作方式类似。下面的代码经过优化,具有有限的 cmets 和异常处理来演示原理。
该示例是一个通用异步方法,因此它可以接受任何可序列化的内容,包括单个和多个文件流:
/// <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)
...
}
}
}
【讨论】: