HttpClient.SendRequestAsync triggering ArgumentException

本文关键字:ArgumentException triggering SendRequestAsync HttpClient | 更新日期: 2023-09-27 18:29:38

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

从拍摄的照片到将照片放入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()

HttpClient.SendRequestAsync triggering ArgumentException

我也遇到了类似的问题。我试图发送一个转换为IInputStreamMemoryStream

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

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