Files通过HttpClient的发布文件的时候是空的

Files通过HttpClient的发布文件的时候是空的

本文介绍了HTT prequest.Files通过HttpClient的发布文件的时候是空的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

服务器端:

    public HttpResponseMessage Post([FromUri]string machineName)
    {
        HttpResponseMessage result = null;
        var httpRequest = HttpContext.Current.Request;

        if (httpRequest.Files.Count > 0 && !String.IsNullOrEmpty(machineName))
        ...

客户端:

    public static void PostFile(string url, string filePath)
    {
        if (String.IsNullOrWhiteSpace(url) || String.IsNullOrWhiteSpace(filePath))
            throw new ArgumentNullException();

        if (!File.Exists(filePath))
            throw new FileNotFoundException();

        using (var handler = new HttpClientHandler { Credentials=  new NetworkCredential(AppData.UserName, AppData.Password, AppCore.Domain) })
        using (var client = new HttpClient(handler))
        using (var content = new MultipartFormDataContent())
        using (var ms = new MemoryStream(File.ReadAllBytes(filePath)))
        {
            var fileContent = new StreamContent(ms);
            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = Path.GetFileName(filePath)
            };
            content.Add(fileContent);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            var result = client.PostAsync(url, content).Result;
            result.EnsureSuccessStatusCode();
        }
    }

在服务器端HTT prequest.Files集合总是空的。但头(内容长度等等)是正确的。

At the server-side httpRequest.Files collection is always empty. But headers (content-length etc...) are right.

推荐答案

您不应该使用的HttpContext获取中的ASP.NET Web API的文件。看看这个例子写的微软(<一href="http://$c$c.msdn.microsoft.com/ASPNET-Web-API-File-Upload-a8c0fb0d/source$c$c?fileId=67087&pathId=565875642">http://$c$c.msdn.microsoft.com/ASPNET-Web-API-File-Upload-a8c0fb0d/source$c$c?fileId=67087&pathId=565875642).

You shouldn't use HttpContext for getting the files in ASP.NET Web API. Take a look at this example written by Microsoft (http://code.msdn.microsoft.com/ASPNET-Web-API-File-Upload-a8c0fb0d/sourcecode?fileId=67087&pathId=565875642).

public class UploadController : ApiController
{
    public async Task<HttpResponseMessage> PostFile()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);

        try
        {
            StringBuilder sb = new StringBuilder(); // Holds the response body

            // Read the form data and return an async task.
            await Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the form data.
            foreach (var key in provider.FormData.AllKeys)
            {
                foreach (var val in provider.FormData.GetValues(key))
                {
                    sb.Append(string.Format("{0}: {1}\n", key, val));
                }
            }

            // This illustrates how to get the file names for uploaded files.
            foreach (var file in provider.FileData)
            {
                FileInfo fileInfo = new FileInfo(file.LocalFileName);
                sb.Append(string.Format("Uploaded file: {0} ({1} bytes)\n", fileInfo.Name, fileInfo.Length));
            }
            return new HttpResponseMessage()
            {
                Content = new StringContent(sb.ToString())
            };
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

}

这篇关于HTT prequest.Files通过HttpClient的发布文件的时候是空的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 20:02