C# 如何同时传递参数并将文件上载到Web API控制器方法?

C# 如何同时传递参数并将文件上载到Web API控制器方法?,c#,http,asp.net-web-api,compact-framework,multipartform-data,C#,Http,Asp.net Web Api,Compact Framework,Multipartform Data,我决定我的问题并不是我真正想做什么——我需要发送的XML可能比我真正想在URI中发送的要长得多 它“觉得”这样做不对,于是拆封了这笔交易 我需要从客户端(手持/CF)应用程序向我的Web API应用程序发送两个参数和一个文件 我可能在这里找到了接收密码[ 具体来说,Wasson的控制器代码在这里看起来可能非常有效: public async Task<HttpResponseMessage> PostFile() { // Check if the request cont

我决定我的问题并不是我真正想做什么——我需要发送的XML可能比我真正想在URI中发送的要长得多

它“觉得”这样做不对,于是拆封了这笔交易

我需要从客户端(手持/CF)应用程序向我的Web API应用程序发送两个参数和一个文件

我可能在这里找到了接收密码[

具体来说,Wasson的控制器代码在这里看起来可能非常有效:

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);
    }
}
…但这取决于

更新2 但事实并非如此

更新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()添加更多调用来实现吗?这是否合理(第一行和第三行不同):

?

更新4 进展情况:尽管如此,它仍在发挥作用:

服务器代码:

public string PostArgsAndFile([FromBody] string value, string serialNum, string siteNum)
{
    string s = string.Format("{0}-{1}-{2}", value, serialNum, siteNum);
    return s;
}
客户代码(来自中的Darin Dimitrov):


现在,我需要让它在[FromBody]参数中发送一个文件而不是字符串。

您应该研究使用多部分/表单数据和自定义媒体类型格式化程序,该格式化程序将提取字符串属性和上载的XML文件

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();
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
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);
    }
}