Xamarin iOS向HttpClient添加Content-Length标头会引发错误

时间:2015-04-07 03:07:50

标签: ios xamarin httpclient azure-storage-blobs content-length

我正在尝试使用HttpClient通过Xamarin.iOS中的REST api将文件上传到Microsoft Azure Blob存储。直到现在它一直没用。每次我尝试向客户端添加Content-Length标头时,都会收到此错误:

System.InvalidOperationException: Content-Length\n  at System.Net.Http.Headers.HttpHeaders.CheckName (System.String name) [0x0005f] in /Developer/MonoTouch/Source/mono/mcs/class/System.Net.Http/System.Net.Http.Headers/HttpHeaders.cs:253 \n  at System.Net.Http.Headers.HttpHeaders.Add (System.String name, IEnumerable`1 values) [0x00011] in /Developer/MonoTouch/Source/mono/mcs/class/System.Net.Http/System.Net.Http.Headers/HttpHeaders.cs:171 \n  at System.Net.Http.Headers.HttpHeaders.Add (System.String name, System.String value) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System.Net.Http/System.Net.Http.Headers/HttpHeaders.cs:163 

这是我创建HttpClient的代码

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Content-Length", blobLength.ToString()); // Error here
client.DefaultRequestHeaders.Add("x-ms-date", dateInRfc1123Format);
client.DefaultRequestHeaders.Add("x-ms-version", msVersion);
Debug.WriteLine("Added all headers except Authorization");
client.DefaultRequestHeaders.Add("Authorization", authorizationHeader);


Debug.WriteLine("Added Authorization header");
//logRequest(requestContent, uri);

Debug.WriteLine("created new http client");
HttpContent requestContent = new ByteArrayContent(blobckContent);
HttpResponseMessage response = await client.PutAsync(uri, requestContent);

我尝试使用TryAddWithoutValidation而不是Add:

client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Length", blobLength.ToString());

错误没有被抛出,但标题仍然没有被添加。 任何帮助都会很棒。

1 个答案:

答案 0 :(得分:0)

这是CheckName()的内部工作方式,它抛出异常。您可以在此处找到来源:https://github.com/mono/mono/blob/master/mcs/class/System.Net.Http/System.Net.Http.Headers/HttpHeaders.cs

HeaderInfo CheckName (string name)
    {
        if (string.IsNullOrEmpty (name))
            throw new ArgumentException ("name");

        Parser.Token.Check (name);

        HeaderInfo headerInfo;
        if (known_headers.TryGetValue (name, out headerInfo) && (headerInfo.HeaderKind & HeaderKind) == 0) {
            if (HeaderKind != HttpHeaderKind.None && ((HeaderKind | headerInfo.HeaderKind) & HttpHeaderKind.Content) != 0)
                throw new InvalidOperationException (name);

            return null;
        }

        return headerInfo;
    }

查看完整的源文件后:

Content-Length的集合中看起来known_headers

看起来Content-Length标头值的内部类型也很长。但是Add()方法只为该值取一个字符串,将其解析为long。您为Content-Length值传递的字符串值是否为有效长?