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