当HttpRequest.Content.IsMimeMultipartContent()返回true

时间:2015-09-25 00:01:33

标签: c# rest http httpwebrequest

我需要将一个HTTP请求作为MultiPartFormData发送到REST控制器。它工作正常,但现在我在控制器上的检查声称请求的类型不正确,即使我在调试器中看到请求的类型正确。供参考:

enter image description here

这是调用它的控制台应用程序代码:

using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace QuickUploadTestHarness
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var client = new HttpClient())
            using (var content = new MultipartFormDataContent())
            {
                // Make sure to change API address
                client.BaseAddress = new Uri("http://localhost");

                // Add first file content 
                var fileContent1 = new ByteArrayContent(File.ReadAllBytes(@"C:\<filepath>\test.txt"));
                fileContent1.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = "testData.txt"
                };

                //Add Second file content
                var fileContent2 = new ByteArrayContent(File.ReadAllBytes(@"C:\<filepath>\test.txt"));
                fileContent2.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = "Sample.txt"
                };

                content.Add(fileContent1);
                content.Add(fileContent2);

                // Make a call to Web API
                var result = client.PostAsync("/secret/endpoint/relevant/bits/here/", content).Result;

                Console.WriteLine(result.StatusCode);
                Console.ReadLine();
            }
        }
    }
}

它怎么可能被解释为不是MultiPartFormData?请注意&#34; 使用MultiPartFormDataContent &#34;对于请求

1 个答案:

答案 0 :(得分:6)

对于MultiPartFormDataContent,您可以尝试使用带有content.Addname参数的filename重载。 MSDN MultipartFormDataContent.Add Method (HttpContent, String, String)

问候