Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    }
like image 317
Saravana Kumar Avatar asked Nov 26 '25 11:11

Saravana Kumar


1 Answers

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;
like image 171
Richard Zhang Avatar answered Dec 01 '25 07:12

Richard Zhang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!