我决定,我的问题在这里是不是真的是我想做的事-我需要发送XML是长了不少,潜在的,不是我真正想要的URI来发送。
它没有“感觉”的权利这样做,而这启封交易。
我需要两两参数的个数和文件从客户端(手持/ CF)应用程序发送到我的Web API的应用程序。
我可能已经找到了代码,用于接收,从这里[ http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2]
具体而言,在这里沃森的控制器代码看起来非常好可能的工作:
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);
}
}
......但现在我需要知道如何发送; 从客户其他调用的形式为:
http://<IPAddress>:<portNum>/api/<ControllerName>?arg1=Bla&arg2=Blee
但如何,我需要发送的文件/附加相处过? 这是一个XML文件,但我不希望整个事情追加到URI,因为它可以是相当大的,而且这样做会是窘况怪异。
是否有人知道如何做到这一点?
UPDATE
继tvanfosson下面扔下面包屑,我发现代码在这里 ,我想我可以适应客户端上运行:
var message = new HttpRequestMessage();
var content = new MultipartFormDataContent();
foreach (var file in files)
{
var filestream = new FileStream(file, FileMode.Open);
var fileName = System.IO.Path.GetFileName(file);
content.Add(new StreamContent(filestream), "file", fileName);
}
message.Method = HttpMethod.Post;
message.Content = content;
message.RequestUri = new Uri("http://localhost:3128/api/uploading/");
var client = new HttpClient();
client.SendAsync(message).ContinueWith(task =>
{
if (task.Result.IsSuccessStatusCode)
{
//do something with response
}
});
...但依赖于是否Compact Framework的支持MultipartFormDataContent
更新2
它不,据我怎么能确定哪些.NET功能紧凑架构了?
更新3
使用Bing搜索代码C#的扩展,我泥“H”,选择“我如何”,进入“通过HTTP发送文件”,并得到这个:
WebRequest request = WebRequest.Create("http://www.contoso.com/PostAccepter.aspx ");
request.Method = "POST";
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
当我需要添加一对字符串参数的个数,除了文件(我假设我可以通过POSTDATA字节数组添加),我可以做到这一点通过增加更多的调用dataStream.Write()? IOW,这是合理的(第一和第三行不同):
WebRequest request = WebRequest.Create("http://MachineName:NNNN/api/Bla?str1=Blee&str2=Bloo");
request.Method = "POST";
string postData = //open the HTML file and assign its contents to this, or make it File postData instead of string postData?
// the rest is the same
?
更新4
进展情况:如它,正在努力:
服务器代码:
public string PostArgsAndFile([FromBody] string value, string serialNum, string siteNum)
{
string s = string.Format("{0}-{1}-{2}", value, serialNum, siteNum);
return s;
}
(从达林季米特洛夫客户端代码这个职位 ):
private void ProcessRESTPostFileData(string uri)
{
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var data = "=Short test...";
var result = client.UploadString(uri, "POST", data);
//try this: var result = client.UploadFile(uri, "bla.txt");
//var result = client.UploadData()
MessageBox.Show(result);
}
}
现在,我需要得到它发送一个文件,而不是在[FromBody] ARG的字符串。