'system.argumentexception' 上传分段时

'system.argumentexception' When uploading multipart

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

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

}

# 在 MIME 边界中无效。

来自RFC 2046

The only mandatory global parameter for the "multipart" media type is the boundary parameter, which consists of 1 to 70 characters from a set of characters known to be very robust through mail gateways, and NOT ending with white space. (If a boundary delimiter line appears to end with white space, the white space must be presumed to have been added by a gateway, and must be deleted.) It is formally specified by the following BNF:

boundary := 0*69<bchars> bcharsnospace

bchars := bcharsnospace / " "

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

所以基本上,您应该使用不包含 # 的边界字符串。我建议使用也不包含连字符的连字符,因为边界 lines 无论如何都会有连字符(在开始和结束处)。将它们也放在边界中有点令人困惑。

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