Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setting Response in WebResourceRequested event handler fails with NullReferenceException #219

Closed
mkvonarx opened this issue May 27, 2020 · 16 comments
Labels
bug Something isn't working

Comments

@mkvonarx
Copy link

I'm trying to set a custom response from my C# code inside the WebResourceRequested event handler, but setting the CoreWebView2WebResourceRequestedEventArgs.Response property always fails with a NullReferenceException in Microsoft.Web.WebView2.Core.dll!Microsoft.Web.WebView2.Core.COMDotNetTypeConverter.HttpResponseMessageNetToCOM

Interesting bits from looking at the stack trace:

  • in the CoreWebView2WebResourceRequestedEventArgs.Response setter code COMDotNetTypeConverter.HttpResponseMessageNetToCOM(_nativeCoreWebView2WebResourceRequestedEventArgs.Response, value); I see that _nativeCoreWebView2WebResourceRequestedEventArgs.Response is always null
  • in HttpResponseMessageNetToCOM I see that the code directly accesses the rawResponse rawResponse.StatusCode = (int)response.StatusCode; which then fails with a NullReferenceException

Maybe I'm not using the WebView2 correctly. But I have the impression this might also be a bug. My code basically looks like this (I started with an empty WPF project):

	public partial class MainWindow : Window
	{
		public MainWindow()
		{
			InitializeComponent();
			webView.CoreWebView2Ready += WebView_CoreWebView2Ready;
			webView.EnsureCoreWebView2Async();
		}

		private void WebView_CoreWebView2Ready(object sender, System.EventArgs e)
		{
			webView.CoreWebView2.AddWebResourceRequestedFilter("*", CoreWebView2WebResourceContext.All);
			webView.CoreWebView2.WebResourceRequested += CoreWebView2_WebResourceRequested;
			webView.CoreWebView2.Navigate("http://abcd");
		}

		private void CoreWebView2_WebResourceRequested(object sender, CoreWebView2WebResourceRequestedEventArgs e)
		{
			var response = new HttpResponseMessage();
			response.StatusCode = HttpStatusCode.NotFound;
			e.Response = response;
		}
	}

My environment: .NET 4.8, VS2019 16.6.0, Windows 10 1903, EdgeDev 84.0.516.1, NuGet Microsoft.Web.WebView2.0.9.515-prerelease

@david-risney david-risney added .NET bug Something isn't working labels May 27, 2020
@david-risney
Copy link
Contributor

Great bug report, thanks! We're looking into this.

@Eilon
Copy link

Eilon commented Jun 2, 2020

I believe I'm hitting this exact issue. @david-risney contact me at elipton@microsoft.com if you need additional info.

@david-risney
Copy link
Contributor

Hi @Eilon. I think we understand this one and will work on fixing it but will reach out if necessary and we appreciate the offer. Thanks!

@Eilon
Copy link

Eilon commented Jun 2, 2020

Looking forward to it, thank you! Also happy to test the fix if that would be helpful.

@shawty
Copy link

shawty commented Jun 10, 2020

Another bug report here too, dunno how I missed this one before but I have the same issue in #254 I'll close my issue now that I know it's being tracked here.

@jspuij
Copy link

jspuij commented Jul 6, 2020

So for everyone looking for a workaround, a little reflection will fix it:

		private void CoreWebView2_WebResourceRequested(object sender, CoreWebView2WebResourceRequestedEventArgs e)
		{

                    /// set your Stream responseStream here
                    /// set your string responseContentType here

		    var eventType = e.GetType();

                    var field = eventType.GetField("_nativeCoreWebView2WebResourceRequestedEventArgs", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

                    var nativeArgs = field.GetValue(e);

                    var environment = (CoreWebView2Environment)Control.GetType().GetProperty("Environment", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(Control);
                    field = environment.GetType().GetField("_nativeCoreWebView2Environment", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                    var nativeEnvironment = field.GetValue(environment);

                    var managedStream = Activator.CreateInstance(eventType.Assembly.GetType("Microsoft.Web.WebView2.Core.ManagedIStream"),
                        System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,
                        null, 
                        new object[] { responseStream }, 
                        null);

                    var method = eventType.Assembly.GetType("Microsoft.Web.WebView2.Core.Raw.ICoreWebView2Environment").GetMethod("CreateWebResourceResponse");
                    var response = method.Invoke(nativeEnvironment, new object[] { managedStream, 200, "OK", $"Content-Type: {responseContentType}" });

                    var property = eventType.Assembly.GetType("Microsoft.Web.WebView2.Core.Raw.ICoreWebView2WebResourceRequestedEventArgs").GetProperty("Response");
                    property.SetValue(nativeArgs, response);
		}

@shawty
Copy link

shawty commented Jul 6, 2020

@jspuij Nice one :-) Will try asap.

@shawty
Copy link

shawty commented Jul 15, 2020

@jspuij Just been trying this, and it can't find the "Environment" property it's looking for, fails here:

image

everytime.

The webView control I have in my windows form doesn't appear to have an "Environment" property, public, protected or otherwise :-(

@jspuij
Copy link

jspuij commented Jul 16, 2020

@shawty The Winforms control does not store a reference to the Environment. Best way is to create it yourself. Something like:

    private async Task InitializeAsync()
    {
        webView2Environment = await CoreWebView2Environment.CreateAsync();
        await webView.EnsureCoreWebView2Async(webView2Environment);
    }

@shawty
Copy link

shawty commented Jul 16, 2020

Thanks @jspuij I've just noticed your pull request on my experimental HbbTV browser, so I'll dig into that and take a look.

@omgfizz
Copy link

omgfizz commented Jul 23, 2020

Is there any update on this issue? I'm getting a similar error where I set the Response property and immediately after it says e.Response is null. A little bit after that I get the exception below. It looks like it there is an error setting the response because for some reason the HttpResponseMessage cannot be converted to a COM object.

FYI, I am using the latest nuget package (Microsoft.Web.WebView2 0.9.579-prerelease) and I am building a plain WPF app.

System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=Microsoft.Web.WebView2.Core
StackTrace:
at Microsoft.Web.WebView2.Core.COMDotNetTypeConverter.d__5.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

Here is a slightly different exception if I make use ConfigureAwait(false) inside that event:

**"Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Web.WebView2.Core.Raw.ICoreWebView2WebResourceRequestedEventArgs'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{2D7B3282-83B1-41CA-8BBF-FF18F6BFE320}' failed due to the following error: No such interface supported (0x80004002 (E_NOINTERFACE))."

" at System.StubHelpers.StubHelpers.GetCOMIPFromRCW(Object objSrc, IntPtr pCPCMD, IntPtr& ppTarget, Boolean& pfNeedsRelease)\r\n at Microsoft.Web.WebView2.Core.Raw.ICoreWebView2WebResourceRequestedEventArgs.get_Response()\r\n at Microsoft.Web.WebView2.Core.CoreWebView2WebResourceRequestedEventArgs.set_Response(HttpResponseMessage value)\r\n at WhiteHatter.App.MainWindow.<CoreWebView_WebResourceRequested>d__4.MoveNext() in C:\Users\migue\Documents\GitHub\WhiteHat-DotNet-Tools\WhiteHatter.App\MainWindow.xaml.cs:line 60"**

@dianaqu
Copy link
Contributor

dianaqu commented Aug 6, 2020

Hi folks on this thread. We are making design changes to fix WebResourceRequested related bugs. Here is a API Proposal. People can take a look and provide feedback. #372

Thanks a lot!

@shawty
Copy link

shawty commented Aug 7, 2020

@dianaqu Will do, thanks Diana

@champnic
Copy link
Member

This should now be available in WebView2 SDK 1.0.674-prerelease. If this is still an issue please let us know. Thanks!

@champnic champnic added this to the SDK 1.0.674-prerelease milestone Oct 19, 2020
@mkvonarx
Copy link
Author

looks ok now. thanks!

@Eilon
Copy link

Eilon commented Oct 20, 2020

I can confirm that this works in Mobile Blazor Bindings: dotnet/MobileBlazorBindings#200

Thank you WebView2 team!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

8 participants