dotnet / maui

.NET MAUI is the .NET Multi-platform App UI, a framework for building native device applications spanning mobile, tablet, and desktop.
https://dot.net/maui
MIT License
22.21k stars 1.75k forks source link

[regression/8.0.0-rc.2.9373] Setting Cookies on .NET MAUI WebView on Windows throws NullReferenceException #18452

Open bdizzleog opened 1 year ago

bdizzleog commented 1 year ago

Description

Was trying to create a webview with cookies on my .net maui blazor hybrid app but upon testing Windows I received a NullReferenceException in Microsoft.Maui.dll.

I created a new .NET MAUI Windows app and created the following:

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiApp1.MainPage">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <StackLayout Grid.Row="1" Padding="10">
            <WebView
        x:Name="myWebView"
        HorizontalOptions="FillAndExpand"
        VerticalOptions="FillAndExpand" />
        </StackLayout>
    </Grid>

</ContentPage>

MainPage.xaml.cs

using System.Net;

namespace MauiApp1
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

            const string url = "https://www.google.com";

            CookieContainer cookieContainer = new();
            Uri uri = new(url, UriKind.RelativeOrAbsolute);

            Cookie cookie = new()
            {
                Name = "DotNetMAUICookie",
                Expires = DateTime.Now.AddDays(1),
                Value = "My cookie",
                Domain = uri.Host,
                Path = "/"
            };

            cookieContainer.Add(uri, cookie);
            myWebView.Cookies = cookieContainer;
            myWebView.Source = new UrlWebViewSource { Url = uri.ToString() };
        }
    }
}

The webview with cookies works as expected on Android. I did not test on iOS/Mac.

Steps to Reproduce

  1. Create new .NET MAUI on .NET 8 RC2
  2. Add WebView to MainPage.xaml
  3. Set WebView.Cookies to new CookieContainer
  4. Start Windows app
  5. Throws null reference exception

Link to public reproduction project repository

No response

Version with bug

8.0.0-rc.2.9373

Is this a regression from previous behavior?

Yes, this used to work in .NET MAUI

Last version that worked well

6.0

Affected platforms

Windows

Affected platform versions

No response

Did you find any workaround?

No workaround on Windows. Webview with cookies works as expected on Android. Not tested on iOS/Mac.

Relevant log output

Exception thrown: 'System.NullReferenceException' in Microsoft.Maui.dll
Object reference not set to an instance of an object.
XamlTest commented 1 year ago

Verified this on Visual Studio Enterprise 17.8.0 Preview 5.0(8.0.0-rc.2.9373). Repro on Windows 11, not repro on Android 14.0-API34 with below Project: 18452.zip

image

ghost commented 11 months ago

We've added this issue to our backlog, and we will work to address it as time and resources allow. If you have any additional information or questions about this issue, please leave a comment. For additional info about issue management, please read our Triage Process.

gameDNA-Helix commented 9 months ago

I can confirm this issue. I ask to fix as soon as possible.

Monarkos commented 9 months ago

This is a stopper for my project... Any news?

HavenDV commented 4 months ago

Still actual on MAUI 8.0.60. StackTrace:

System.NullReferenceException
Object reference not set to an instance of an object.

Task<IReadOnlyList<CoreWebView2Cookie>> WebViewHandler.GetCookiesFromPlatformStore(string url)
async Task WebViewHandler.InitialCookiePreloadIfNecessary(string url)
async Task WebViewHandler.SyncPlatformCookies(string url)
async void MauiWebView.LoadUrl(string url)
Task.cs in void Task.ThrowAsync(Exception exception, SynchronizationContext targetContext)+(object state) => { } at line 1914
void DispatcherQueueSynchronizationContext.Post(SendOrPostCallback d, object state)+() => { }

Completely eliminates the point of a universal WebView for certain use cases

HavenDV commented 4 months ago

Workaround to get current cookies on Windows. Perhaps it will be useful to someone before the official correction

#if WINDOWS
using System.Net;
using Microsoft.UI.Xaml.Controls;
using WebView = Microsoft.Maui.Controls.WebView;

#nullable enable

namespace Extensions;

public static class WebViewExtensions
{
    public static async Task<CookieCollection> GetCookies(this WebView webView, Uri uri)
    {
        return await MainThread.InvokeOnMainThreadAsync(async () =>
        {
            var webView2 = webView?.Handler?.PlatformView as WebView2;
            var cookieManager = webView2?.CoreWebView2.CookieManager;
            if (cookieManager == null)
            {
                return new CookieCollection();
            }

            var cookies = await cookieManager.GetCookiesAsync(uri.ToString());
            var cookieCollection = new CookieCollection();
            foreach (var cookie in cookies)
            {
                cookieCollection.Add(new System.Net.Cookie
                {
                    Name = cookie.Name,
                    Value = cookie.Value,
                    Domain = cookie.Domain,
                    Path = cookie.Path,
                    Expires = DateTime.MinValue,
                    HttpOnly = cookie.IsHttpOnly,
                    Secure = cookie.IsSecure
                });
            }

            return cookieCollection;
        });
    }
}
#endif
rocksoldi commented 1 month ago

Any news with this ? A workaround which allow setting cookies from Webview ?