使用Web Client从流中发布multipart / form-data文件

时间:2016-07-08 17:00:38

标签: c# webclient multipartform-data

问题:是否可以使用Web客户端将HttpPostedFileBase(仅在内存中可用,而不是在磁盘上)发布到另一个端点?

我尝试了什么:

我有以下控制器,我们在前端的文件中发布,它绑定到文件参数。

public class HomeController : Controller
{
    [System.Web.Http.HttpPost]
    public async Task<string> Index(HttpPostedFileBase file)
    {
        //file is not null here, everything works as it should.

        //Here im preparing a multipart/form-data request to my api endpoint
        var fileStreamContent = new StreamContent(file.InputStream);
        using (var client = new HttpClient())
        using (var formData = new MultipartFormDataContent())
        {
            formData.Add(fileStreamContent);
            var response = await client.PostAsync("http://restapi.dev/api/files/add", formData);
            var result = await response.Content.ReadAsStringAsync();
            return result;
        }
    }
}

我需要将此请求传递给另一个不公开的应用程序(因此我们无法直接从客户端发布) 那个控制器看起来像这样:

[RoutePrefix("api/files")]
public class FilesController : ApiController
{
    [HttpPost]
    [Route("add")]
    public async Task<HttpResponseMessage> Add(HttpPostedFileBase file)
    {
        //This is the problem, file is always null when I post from my backend.
        var files = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;
        return Request.CreateResponse(HttpStatusCode.OK);
    }
}

file始终为空,files也是如此。 我错过了什么?当我使用postman并直接发布到API端点时,它可以工作。所以我猜测我在HomeController做错了什么?

1 个答案:

答案 0 :(得分:1)

您可以使用更新的技术改进这一点。

在webapi中,您可以编写如下控制器方法:

//[Route("api/Foo")] //maybe?
[HttpPost]
public async Task<HttpResponseMessage> MyResourceProxy(HttpRequestMessage request)

现在您可以接受该请求并重写其RequestUri属性:

request.RequestUri = new Uri(blah);

新增HttpClient并转发请求:

HttpClient client = new HttpClient();
//make sure that this fails if it's hung for more than 30 seconds
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
try
{
    response = await client.SendAsync(request,
                                      HttpCompletionOption.ResponseHeadersRead, 
                                      cts.Token);
}
catch (TaskCanceledException)
{
    response = new HttpResponseMessage(HttpStatusCode.GatewayTimeout);
}

确保一切都被处理掉:

request.RegisterForDispose(new IDisposable[] {request, client, cts, response});

然后返回response

return response;

我添加了一个超时机制,可能不适合您的需要。