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

Peterjc 91 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

Developer technologies | Windows Presentation Foundation
Developer technologies | ASP.NET | ASP.NET API
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.