以 Windows 10 UWP 为目标时,PostAsync 抛出 IRandomAccessStream 错误 [英] PostAsync throwing IRandomAccessStream error when targeting windows 10 UWP

查看:21
本文介绍了以 Windows 10 UWP 为目标时,PostAsync 抛出 IRandomAccessStream 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将我的 Windows 8.1 应用程序移植到 Windows 10 UWP,但现在调用 PostAsync 会引发异常.

I'm in the process of porting my windows 8.1 app to windows 10 UWP, but calling PostAsync now throws an exception.

这个确切的代码在面向 8.1 时完美运行,但是当我面向 Windows 10 UWP 时,它会引发以下异常:

This exact code works perfectly when targeting 8.1, but when I target Windows 10 UWP, it throws the following exception:

此 IRandomAccessStream 不支持 GetInputStreamAt 方法,因为它需要克隆,而此流不支持克隆.

代码

    public async void TestPost()
    {
        var parameters = GetParameters();
        var formattedData = new FormUrlEncodedContent(parameters);
        using (var clientHandler = new HttpClientHandler { Credentials = GetCredentials() })
        {
            using (var httpClient = new HttpClient(clientHandler))
            {
                var response = await httpClient.PostAsync(postUrl, formattedData);
            }
        }
    }

private Dictionary<string, string> GetParameters()
{
    var parameters = new Dictionary<string, string>();
    parameters["grant_type"] = "url";
    parameters["device_id"] = "unique key";
    parameters["redirect_uri"] = "redirect url";
    return parameters;
}

public static NetworkCredential GetCredentials()
{
    return new NetworkCredential("<secret key>", "");
}

堆栈跟踪

 at System.IO.NetFxToWinRtStreamAdapter.ThrowCloningNotSuported(String methodName)
   at System.IO.NetFxToWinRtStreamAdapter.GetInputStreamAt(UInt64 position)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.Http.HttpHandlerToFilter.<SendAsync>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.Http.HttpClientHandler.<SendAsync>d__1.MoveNext()

推荐答案

您是否尝试过使用 Windows.Web.Http.HttpClient 代替?

Have you tried using Windows.Web.Http.HttpClient instead?

// using Windows.Web.Http;
// using Windows.Web.Http.Filters;

var parameters = GetParameters();
var formattedData = new HttpFormUrlEncodedContent(parameters);
using (var clientHandler = new HttpBaseProtocolFilter())
{
    clientHandler.ServerCredential = GetCredentials();

    using (var httpClient = new HttpClient(clientHandler))
    {
        var response = await httpClient.PostAsync(postUrl, formattedData);
    }
}

这篇关于以 Windows 10 UWP 为目标时,PostAsync 抛出 IRandomAccessStream 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆