Ionic application running within WPF using webview2 get CORS error if trying to connect to a localhost Asp.NET WebAPI server

Peterjc 81 Reputation points
2023-04-07T02:45:14.7966667+00:00

Hi, I have an Ionic application I am running within a .net 6 WPF application where it is hosted within WebView2. I have an asp.net WebAPI (/net framework 4.8) running on both my local dev machine (Windows 11), and a remote azure server. The WPF/Ionic application can connect an ajax call to the instance on the azure server no problems, however, when I try to connect to an instance running on my local machine, using the WebView 2 devtools, I see the following error

Access to XMLHttpRequest at 'http://localhost/test' from origin 'http://app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I have the following code in the webview application.

// Map the folder the Ionic app to a virtual host name we can then use as a web view source
string appSourceFolder = $"{AppDomain.CurrentDomain.BaseDirectory}_app";
AppWebView.CoreWebView2.SetVirtualHostNameToFolderMapping(
    app", appSourceFolder, CoreWebView2HostResourceAccessKind.Allow);

AppWebView.Source = new Uri("http://app/index.html");

I remember when I was running the same app in a UWP we had to register the container etc to be able to connect to localhost, but I was sure we were now over this hurdle. Any ideas why I have having this problem Connecting to my local host, but not another instance of the server running elsewhere? Thanks in advance

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,686 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
306 questions
{count} votes