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

前端之家收集整理的这篇文章主要介绍了c# – 通过HttpClient发布文件时,HttpRequest.Files为空前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
服务器端:
  1. public HttpResponseMessage Post([FromUri]string machineName)
  2. {
  3. HttpResponseMessage result = null;
  4. var httpRequest = HttpContext.Current.Request;
  5.  
  6. if (httpRequest.Files.Count > 0 && !String.IsNullOrEmpty(machineName))
  7. ...

客户端:

  1. public static void PostFile(string url,string filePath)
  2. {
  3. if (String.IsNullOrWhiteSpace(url) || String.IsNullOrWhiteSpace(filePath))
  4. throw new ArgumentNullException();
  5.  
  6. if (!File.Exists(filePath))
  7. throw new FileNotFoundException();
  8.  
  9. using (var handler = new HttpClientHandler { Credentials= new NetworkCredential(AppData.UserName,AppData.Password,AppCore.Domain) })
  10. using (var client = new HttpClient(handler))
  11. using (var content = new MultipartFormDataContent())
  12. using (var ms = new MemoryStream(File.ReadAllBytes(filePath)))
  13. {
  14. var fileContent = new StreamContent(ms);
  15. fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
  16. {
  17. FileName = Path.GetFileName(filePath)
  18. };
  19. content.Add(fileContent);
  20. content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
  21.  
  22. var result = client.PostAsync(url,content).Result;
  23. result.EnsureSuccessStatusCode();
  24. }
  25. }

在服务器端,httpRequest.Files集合始终为空.但标题(内容长度等)是正确的.

解决方法

您不应该使用HttpContext来获取ASP.NET Web API中的文件.看看这个由微软( http://code.msdn.microsoft.com/ASPNET-Web-API-File-Upload-a8c0fb0d/sourcecode?fileId=67087&pathId=565875642)编写的例子.
  1. public class UploadController : ApiController
  2. {
  3. public async Task<HttpResponseMessage> PostFile()
  4. {
  5. // Check if the request contains multipart/form-data.
  6. if (!Request.Content.IsMimeMultipartContent())
  7. {
  8. throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
  9. }
  10.  
  11. string root = HttpContext.Current.Server.MapPath("~/App_Data");
  12. var provider = new MultipartFormDataStreamProvider(root);
  13.  
  14. try
  15. {
  16. StringBuilder sb = new StringBuilder(); // Holds the response body
  17.  
  18. // Read the form data and return an async task.
  19. await Request.Content.ReadAsMultipartAsync(provider);
  20.  
  21. // This illustrates how to get the form data.
  22. foreach (var key in provider.FormData.AllKeys)
  23. {
  24. foreach (var val in provider.FormData.GetValues(key))
  25. {
  26. sb.Append(string.Format("{0}: {1}\n",key,val));
  27. }
  28. }
  29.  
  30. // This illustrates how to get the file names for uploaded files.
  31. foreach (var file in provider.FileData)
  32. {
  33. FileInfo fileInfo = new FileInfo(file.LocalFileName);
  34. sb.Append(string.Format("Uploaded file: {0} ({1} bytes)\n",fileInfo.Name,fileInfo.Length));
  35. }
  36. return new HttpResponseMessage()
  37. {
  38. Content = new StringContent(sb.ToString())
  39. };
  40. }
  41. catch (System.Exception e)
  42. {
  43. return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,e);
  44. }
  45. }
  46.  
  47. }

猜你在找的C#相关文章