c# - 通过 HttpClient 发布文件时 HttpRequest.Files 为空

标签 c# .net asp.net-web-api 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();
        }
    }   

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

最佳答案

您不应使用 HttpContext 获取 ASP.NET Web API 中的文件。看看这个由 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); 
        } 
    } 

}

关于c# - 通过 HttpClient 发布文件时 HttpRequest.Files 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15543150/

相关文章:

c# - 如何隐藏公共(public)程序集类?

c# - Web API 操作返回类型最佳实践

c# - 特定列的 GridView 排序

c# - 控制台应用程序的返回码

C# for 循环语法

javascript - 如何从 Angular JS 中的 HttpResponse 中提取 JSON 数据?

web-services - 在服务器上运行 asp.net WebAPI,无需安装 asp.net mvc 4 beta

c# - 适用于 ReSharper 的 StyleCop

c# - .NET 将简单数组转换为列表泛型

C#:对于空列表,Any() 与 Count()