我正在UWP Web视图中导航到一个URL,该页面在内部进行了许多http调用。我正在通过WebResourceRequested事件拦截这些呼叫。我在标头中添加了auth令牌,这样做时,我得到了“ 应用程序被称为已编入不同线程的接口”,试图在当前UI的调度程序中运行,但仍然遇到此问题。请帮助我。
private async void Wb_WebResourceRequested(WebView sender, WebViewWebResourceRequestedEventArgs args)
{
//_ = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
//{
try
{
string host = args.Request.RequestUri.Host;
string uri = args.Request.RequestUri.AbsoluteUri;
try
{
var reqMsg = args.Request;
reqMsg.Headers.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Bearer", _AuthToken);
var response = await client.SendRequestAsync(reqMsg).AsTask();
args.Response = response;
Debug.WriteLine(uri + " res code : " + response.StatusCode);
}
catch (Exception e)
{
Debug.WriteLine(uri + " error msg : " + e.Message);
}
}
catch (Exception e)
{
}
//});
}
根据测试,设置args.Response
时不能处于异步环境。
请更改
var response = await client.SendRequestAsync(reqMsg).AsTask();
至:
var response = client.SendRequestAsync(reqMsg).AsTask().Result;