【问题标题】:How to send file to end-point RESTful C#?如何将文件发送到端点 RESTful C#?
【发布时间】:2017-06-01 21:15:21
【问题描述】:

为了向服务器发送数据,我使用这个解决方案:

https://stackoverflow.com/a/19664927/8033752

但是如何通过 POST 将数据发送到具体的端点 RESTful?

【问题讨论】:

  • 你所说的“宁静”是什么意思? REST API 只是一个 HTTP 端点,REST 部分不会改变底层 HTTP 请求的语义。

标签: c# wpf winforms c#-4.0


【解决方案1】:

我就是这样做的——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)
            ...
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 2018-09-23
    • 2020-05-20
    • 2018-08-14
    • 2020-10-29
    相关资源
    最近更新 更多