Search code examples
c#wpfasp.net-web-api

WPF (.Net 6.0) GUI app with REST API service (ASP.Net WebAPI)


I have a WPF app and would like to make it controllable through REST api. I have tried out the ASP.Net minimal web API sample project and found it runnable and useful enough. However, I have limited idea of how to integrate the two.

Starting from the standard .Net 6.0 WPF app, I made the following modifications to the Project File:

1. Changing <Project Sdk="Microsoft.NET.Sdk"> to <Project Sdk="Microsoft.NET.Sdk.Web">.
2. Adding PackageReference as <PackageReference Include="Swashbuckle.AspNetCore" Version="6.3.1" />.
3. Removing the <StartupObject> line.

And I copied the default Program.cs (defining the Web API services, as shown in the tutorial web page) file from the web API sample project to my WPF project with necessary namespaces added to get rid off the reference errors. At this point, I am able to launch the WPF app and activate the WebAPI but cannot launch the WPF Window now: initializing that variable in the web API would raise an exception

The calling thread must be STA, because many UI components require this

How may I have the WPF GUI and the Web API working together?


Solution

  • You can host an ASP.NET Web API inside a WPF app as suggested here.

    You should not change the project SDK though, i.e. you still need the Microsoft.NET.Sdk and the <UseWPF> setting to be able to build the desktop app.