HttpClient.SendRequestAsync触发ArgumentException

时间:2016-01-08 11:31:53

标签: c# windows-phone-8.1

每当用户想要更改照片时,我都会尝试将照片上传到服务器。

拍摄的照片一切正常,将照片转换为IRandomAccessStreamHttpMultipartFormDataContent,但当我尝试发送请求时,会抛出ArgumentException

对于我在调试中看到的内容,似乎没有任何错误,但无论如何都会抛出异常。

以下是代码:

public static async Task<WebResult> UploadImage( WebHost webHost, Object webPath, String webQuery, IRandomAccessStream imageStream ) {

    /* ... */

    HttpClient
        httpClient = new Windows.Web.Http.HttpClient();

    HttpMultipartFormDataContent
        httpMultipartContent = new HttpMultipartFormDataContent();

    HttpStreamContent
        httpStreamContent = new HttpStreamContent( imageStream );

    httpStreamContent.Headers.Add( "Content-Type", "application/octet-stream" );
    httpMultipartContent.Add( httpStreamContent, "userAvatar", DateTime.Now.Ticks.ToString( "yyyyMMddhhmmssffff" ) + ".png" );

    try {
        HttpRequestMessage
            httpRequest = new HttpRequestMessage( HttpMethod.Post, new Uri( /* ... */ ) );

        Dictionary<String, String>
            webCredentialsDictionary = WebServerAuthenticationCredentials( /* ... */ ) as Dictionary<String, String>;

        foreach (KeyValuePair<String, String> credentialEntry in webCredentialsDictionary) {
            httpRequest.Headers.Add( credentialEntry );
        }

        httpRequest.Content = httpMultipartContent;

        /* The ArgumentException is thrown here. */
        HttpResponseMessage
            httpResponse = await httpClient.SendRequestAsync( httpRequest );

        httpResponse.EnsureSuccessStatusCode();

        return new WebResult( true, true, null );
    } catch (ArgumentException exception) {

    } catch (Exception exception) {

    }

    /* ... */
}

在执行请求之前是否应该设置任何内容?

此外,这里是堆栈跟踪:

System.ArgumentException: Value does not fall within the expected range.
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at WindowsPhoneFramework.WebController.<UploadImage>d__28.MoveNext()

1 个答案:

答案 0 :(得分:0)

我有类似的问题。我尝试将MemoryStream转换为IInputStream

request.Content = new HttpStreamContent(ms.AsInputStream());

并且解决方案是在将流设置为内容之前将流的位置设置为开头。