Saravana Kumar
Saravana Kumar

Reputation: 379

UWP Intercept Webview request and add header

I'm navigating to a url in UWP webview, the page internally makes many http calls. I'm intercepting those calls via WebResourceRequested event. I'm adding auth token in the header, when doing so I'm getting "application called an interface that was marshalled for a different thread", tried to run in the current UI's dispatcher but still I face this issue. Please help me on this.

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

    }

Upvotes: 3

Views: 810

Answers (1)

Anran Zhang
Anran Zhang

Reputation: 7727

According to tests, you cannot be in an asynchronous environment when setting args.Response.

please change

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

to:

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

Upvotes: 2

Related Questions