将多部分表单数据从Windows Phone发送到web api

时间:2014-07-22 13:15:33

标签: asp.net-mvc-4 asp.net-web-api http-post windows-phone-8.1 http-put

您好我想从Windows Phone 8.1使用HttpClient发送(发布/发送)一些数据(包含string,int和Stream)到web api。什么是最好的方法。

 public async void Put(string uri)
    {
        var httpClient = new System.Net.Http.HttpClient();

        MultipartFormDataContent content = new MultipartFormDataContent();
        var stringContent = new StringContent("FirstName=MUH&LastName=Test", Encoding.UTF8, "multipart/form-data");
        var test = new StreamContent(new MemoryStream());
        content.Add(test);
        content.Add(stringContent);
        var message = await httpClient.PutAsync(url+"/UpdateTest", content);

        message.EnsureSuccessStatusCode();

        string content1 = await message.Content.ReadAsStringAsync();

    }
我的mvc应用程序中的

api方法

 [AllowAnonymous]
    [Route("~/api/account/UpdateTest")]
    [HttpPut]
    public async Task<object> UpdateTest()
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }
        try
        {
            var requestParts = await Request.Content.ReadAsMultipartAsync();
            foreach (var part in requestParts.Contents)
            {
                //part is always StreamContent
                var test = await part.ReadAsStreamAsync();
                var test1 = await part.ReadAsStringAsync();
            }
        }
        catch (Exception ex)
        { }
    }

在我的windows phone项目中,我传递了2个HttpContent,一个是StreamContent,其他是StringContent。但在我的web api put方法中,两者都是StreamContent,我不知道为什么。

和其他问题是我必须在StingContnet中解析字符串键值。我的问题是从Windows Phone 8.1向web api发送/接收多部分表单数据的最佳方式是什么,

由于

2 个答案:

答案 0 :(得分:2)

以下是一个示例(根据您的方案进行相应更改):

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseAddress);

HttpRequestMessage request = new HttpRequestMessage();

MultipartFormDataContent mfdc = new MultipartFormDataContent();
mfdc.Add(new StringContent("Michael"), name: "FirstName");
mfdc.Add(new StringContent("Jordan"), name: "LastName");
mfdc.Add(new StreamContent(content: new MemoryStream(Encoding.UTF8.GetBytes("This is from a file"))), 
        name: "Data", 
        fileName: "File1.txt");

HttpResponseMessage response = await client.PostAsync(baseAddress + "/api/values", mfdc);

public async Task Post()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.BadRequest);
    }

    MultipartFormDataStreamProvider prov = await Request.Content.ReadAsMultipartAsync<MultipartFormDataStreamProvider>(new MultipartFormDataStreamProvider(@"C:\uploadedfiles"));

    // example of how you can read the form data
    string firstName = prov.FormData["FirstName"];

    // Get list of all files that have been uploaded and stored in the above provided root folder 
    Collection<MultipartFileData> files = prov.FileData;
}

以下是 Fiddler工具

中的请求
POST http://localhost:9095/api/values HTTP/1.1
Content-Type: multipart/form-data; boundary="7560a854-a71a-4e55-9571-5c2de520f45f"
Host: kirandesktop:9095
Content-Length: 474
Expect: 100-continue
Connection: Keep-Alive

--7560a854-a71a-4e55-9571-5c2de520f45f
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name=FirstName

Michael
--7560a854-a71a-4e55-9571-5c2de520f45f
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name=LastName

Jordan
--7560a854-a71a-4e55-9571-5c2de520f45f
Content-Disposition: form-data; name=Data; filename=File1.txt; filename*=utf-8''File1.txt

This is from a file
--7560a854-a71a-4e55-9571-5c2de520f45f--

另请注意,您可以随时阅读StreamContent ...在以下示例中,我正在模拟请求的正文流并将其作为简单字符串读取或反序列化为对象输入人物。

StreamContent requestStream = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes("Hello World!")));
string data = await requestStream.ReadAsStringAsync();

//---------------------

StreamContent requestStream = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes("{ \"FirstName\" : \"Michael\" }")));
requestStream.Headers.ContentType = new MediaTypeHeaderValue("application/json");
Person person = await requestStream.ReadAsAsync<Person>();

答案 1 :(得分:1)

我使用自定义媒体类型格式化程序,它基于本文中的代码。

ASP.NET WebApi: MultipartDataMediaFormatter

与MultipartFormDataStreamProvider相比,其中一个优点是我不需要指定一个文件夹来保存文件数据,因此我可以检查内存中的内容。你可能不想用大文件来做这件事。如果你想查看代码,那里也有很多github repo。此外,我获得了文件和表单数据的强类型对象