' system.argumentexception'上传multipart时

时间:2015-03-16 11:12:02

标签: c# windows-phone multipartform-data dotnet-httpclient

我正在尝试使用System.Net.Http.HttpClient发布多部分数据但是当我实现我的内容时,我遇到了这个例外:

A first chance exception of type 'System.ArgumentException' occurred in System.Net.Http.DLL
An exception of type 'System.ArgumentException' occurred in System.Net.Http.DLL and wasn't handled before a managed/native boundary
e: System.ArgumentException: The format of value '---###---' is invalid.
Parameter name: boundary
   at System.Net.Http.MultipartContent.ValidateBoundary(String boundary)
   at System.Net.Http.MultipartContent..ctor(String subtype, String boundary)
   at System.Net.Http.MultipartFormDataContent..ctor(String boundary)
   at RestClientUploadFoto.MultipartStackOverflow.<postMultipart>d__2.MoveNext()
  • 为什么会这样?

这是我获得异常的方法:

public async Task postMultipart()
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/form-data");

    // boundary      
    String boundary = "---###---"; // should never occur in your data

    // This is the postdata
    MultipartFormDataContent content = new MultipartFormDataContent(boundary);
    content.Add(new StringContent("12", Encoding.UTF8), "userId");
    content.Add(new StringContent("78", Encoding.UTF8), "noOfAttendees");
    content.Add(new StringContent("chennai", Encoding.UTF8), "locationName");
    content.Add(new StringContent("32.56", Encoding.UTF8), "longitude");
    content.Add(new StringContent("32.56", Encoding.UTF8), "latitude");

    Console.Write(content);
    // upload the file sending the form info and ensure a result.
    // it will throw an exception if the service doesn't return a valid successful status code
    await client.PostAsync(fileUploadUrl, content)
        .ContinueWith((postTask) =>
        {
            postTask.Result.EnsureSuccessStatusCode();
        });

}

1 个答案:

答案 0 :(得分:3)

#在MIME边界无效。

来自RFC 2046

  

“multipart”媒体类型的唯一强制全局参数是   边界参数,由1到70个字符组成   已知通过邮件网关非常强大的字符集,以及   不以空格结尾。 (如果出现边界定界线   以白色空间结束,必须假设白色空间已经存在   由网关添加,必须删除。)它是正式指定的   由以下BNF:

boundary := 0*69<bchars> bcharsnospace

bchars := bcharsnospace / " "

bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
                 "+" / "_" / "," / "-" / "." /
                 "/" / ":" / "=" / "?"

所以基本上,你应该使用一个不包含#的边界字符串。我建议使用一个不包含连字符的,只是因为边界 line 无论如何都会有连字符(在开头和结尾)。将它们放在边界也有点令人困惑。

除非您需要特定的边界,否则我建议您调用无参数构造函数,它将使用随机GUID作为边界。

相关问题