You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin Forms中如何拦截WebView返回的重定向URL

解决方案

你需要通过WebView的Navigating事件拦截导航请求,该事件会在WebView加载新URL前触发,你可以在事件回调中判断是否为OAuth重定向地址,再提取对应参数。


步骤1:修改XML文件,为WebView绑定导航事件

给你的WebView控件添加Navigating属性,绑定事件处理方法:

<ContentPage.Content>
    <WebView x:Name="browser" Navigating="Browser_Navigating"></WebView>
</ContentPage.Content>

步骤2:修改CS文件,实现事件逻辑

在页面对应的CS类中添加Navigating事件的处理方法,在方法内判断重定向地址、提取参数:

public partial class YourPage : ContentPage
{
    public YourPage()
    {
        InitializeComponent();
        browser.Source = "https://myUrl";
    }

    private void Browser_Navigating(object sender, WebNavigatingEventArgs e)
    {
        // 替换为你OAuth应用预设的重定向地址前缀
        const string OAuthRedirectUri = "https://your-redirect-uri.com/callback";
        
        // 匹配到OAuth重定向地址时处理
        if (e.Url.StartsWith(OAuthRedirectUri))
        {
            // 取消WebView加载重定向地址,无需展示回调页
            e.Cancel = true;
            
            // 解析URL参数
            Uri redirectUri = new Uri(e.Url);
            
            // 提取Query参数(适用于授权码流,拿code参数)
            var queryParams = System.Web.HttpUtility.ParseQueryString(redirectUri.Query);
            string authCode = queryParams.Get("code");
            
            // 如果是隐式流,参数在#后,取Fragment解析即可
            // string fragment = redirectUri.Fragment.TrimStart('#');
            
            // 拿到参数后执行后续业务逻辑,比如用code换access_token
            HandleAuthResult(authCode);
        }
    }

    private void HandleAuthResult(string authCode)
    {
        // 你的后续业务逻辑
    }
}

补充说明

如果你的项目引用System.Web有冲突,可以自行实现简单的URL参数解析逻辑,拆分&和=即可拿到对应键值对。

内容的提问来源于stack exchange,提问作者JBD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 20:27:03