【问题标题】:HttpRequest.Content.IsMimeMultipartContent() is returning false when it should return trueHttpRequest.Content.IsMimeMultipartContent() 在应该返回 true 时返回 false
【发布时间】:2015-09-25 00:01:32
【问题描述】:

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

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

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?请注意请求的“using MultiPartFormDataContent

【问题讨论】:

    标签: c# rest http httpwebrequest


    【解决方案1】:

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

    【讨论】:

    • 对不起...我听不懂。你能告诉我我必须在我的控制器上更改什么以使 IsMimeMultipartContent() 返回 true 吗?我从 web 客户端发送文件,而不是 asp,并在我的 webapi 控制器上接收。
    • 已解决...只需从邮递员请求中取出内容类型,一切正常。
    • 是的,我也注意到了,但这真的很奇怪。为什么 Content-Type 标头设置正确时会失败,而缺少时却成功?
    猜你喜欢
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多