UWP拦截Webview请求并添加标题

问题描述 投票:0回答:1

我正在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)
            {
            }
        //});

    }
uwp winrt-xaml uwp-xaml
1个回答
0
投票

根据测试,设置args.Response时不能处于异步环境。

请更改

var response = await client.SendRequestAsync(reqMsg).AsTask();

至:

var response = client.SendRequestAsync(reqMsg).AsTask().Result;
© www.soinside.com 2019 - 2024. All rights reserved.