微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

服务器端:
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集合始终为空.但标题(内容长度等)是正确的.

解决方法

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

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐