加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在UWP中设置自定义WebView标头

发布时间:2020-12-15 08:20:07 所属栏目:百科 来源:网络整理
导读:这似乎与其他 similar问题重复,但它们是旧线程,并不是Windows UWP应用程序特有的. 我无法在WebView中设置自定义标头,因此WebView中加载的URL可能对我有用. 我见过许多论坛提供解决方案,比如使用带有标头的HttpClient / WebRequest但是在我的情况下不起作用,
这似乎与其他 similar问题重复,但它们是旧线程,并不是Windows UWP应用程序特有的.

我无法在WebView中设置自定义标头,因此WebView中加载的URL可能对我有用.

我见过许多论坛提供解决方案,比如使用带有标头的HttpClient / WebRequest但是在我的情况下不起作用,用于重定向的Web地址使用Javascript,在重定向之前,它需要很少的自定义标头才能正确加载.

此外WebView.NavigateWithHttpRequestMessage不太合适,因为它将回发,我需要每个请求的标题,包括web View中的javascript重定向的URL.

我可以使用Renderers在Xamarin.Droid项目中设置自定义标题,但我找不到任何UWP Windows.UI.Xaml.Controls.WebView的解决方案.

解决方法

在通用Windows 10平台上,WebView.NavigateWithHttpRequestMessage方法是正确的方法.

a. I need the headers for each request including javascript redirected URLs in web View.

b. This didn’t resolve my issue as after setting the headers the OnWebViewNavigationStarting method is called multiple times and App crashes automatically with System.StackOverflowException error

这是因为如果我们在NavigationStarting事件中进行导航,将会发生无限导航.我们应该通过将WebViewNavigationStartingEventArgs.Cancel属性设置为true来取消此事件的处理程序中的导航.

我们需要仔细添加/删除NavigationStarting事件的处理程序.

代码示例:

private void NavigateWithHeader(Uri uri)
    {
        var requestMsg = new Windows.Web.Http.HttpRequestMessage(HttpMethod.Get,uri);
        requestMsg.Headers.Add("User-Name","Franklin Chen");
        wb.NavigateWithHttpRequestMessage(requestMsg);

        wb.NavigationStarting += Wb_NavigationStarting;
    }

    private void Button_Click(object sender,RoutedEventArgs e)
    {
        NavigateWithHeader(new Uri("http://openszone.com/RedirectPage.html"));
    }

    private void Wb_NavigationStarting(WebView sender,WebViewNavigationStartingEventArgs args)
    {
        wb.NavigationStarting -= Wb_NavigationStarting;
        args.Cancel = true;//cancel navigation in a handler for this event by setting the WebViewNavigationStartingEventArgs.Cancel property to true
        NavigateWithHeader(args.Uri);
    }

屏幕截图是Fiddler中的日志信息,第二个红色矩形中的请求记录包括自定义标头:

我在here分享了我的UWP示例,您可以轻松地集成到您的Xamarin UWP应用程序中.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读