[ACCEPTED]-Hosting ASP.NET Core API in a Windows Forms Application-asp.net-core-webapi

Accepted answer
Score: 37

Hosting ASP.NET CORE API in a Windows Forms Application and Interaction with Form

Here is a basic step by step example about 9 how to create a project to host ASP.NET 8 CORE API inside a Windows Forms Application 7 and perform some interaction with Form.

To 6 do so, follow these steps:

  1. Create a Windows Forms Application name it MyWinFormsApp
  2. Open Form1 in design mode and drop a TextBox on it.
  3. Change the Modifiers property of the textBox1 in designer to Public and save it.
  4. Install Microsoft.AspNetCore.Mvc package
  5. Install Microsoft.AspNetCore package
  6. Create a Startup.cs file 5 in the root of the project, and copy the 4 following code:

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    namespace MyWinFormsApp
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
            public IConfiguration Configuration { get; }
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            }
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                app.UseMvc();
            }
        }
    }
    
  7. Copy the following code in 3 Program.cs:

    using System;
    using System.Threading;
    using System.Windows.Forms;
    using Microsoft.AspNetCore;
    using Microsoft.AspNetCore.Hosting;
    
    namespace MyWinFormsApp
    {
        public class Program
        {
            public static Form1 MainForm { get; private set; }
    
            [STAThread]
            public static void Main(string[] args)
            {
                CreateWebHostBuilder(args).Build().RunAsync();
    
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                MainForm = new Form1();
                Application.Run(MainForm);
            }
    
            public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
                WebHost.CreateDefaultBuilder(args)
                    .UseStartup<Startup>();
        }
    }
    
  8. Create a folder called Controllers in the root of 2 the project.

  9. Create ValuesController.cs in the Controllers folder and copy 1 the following code to file:

    using System;
    using Microsoft.AspNetCore.Mvc;
    
    namespace MyWinFormsApp.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class ValuesController : ControllerBase
        {
            [HttpGet]
            public ActionResult<string> Get()
            {
                string text = "";
                Program.MainForm.Invoke(new Action(() =>
                {
                    text = Program.MainForm.textBox1.Text;
                }));
                return text;
            }
    
            [HttpGet("{id}")]
            public ActionResult Get(string id)
            {
                Program.MainForm.Invoke(new Action(() =>
                {
                    Program.MainForm.textBox1.Text = id;
                }));
                return Ok();
            }
        }
    }
    
  10. Run the application.

  11. Type "hi" in the textBox1
  12. Open browser and browse http://localhost:5000/api/values → You will see hi as response.
  13. http://localhost:5000/api/values/bye → You will see bye in textBox1
Score: 0

I Install Microsoft.AspNetCore.Mvc and Microsoft.AspNetCore package can't use

I look 7 at this WebApplication.CreateBuilder Method Doc find need Microsoft.AspNetCore.dll, but 6 I can't use this.

I hope it helps others.


Install 5 Microsoft.AspNetCore.App package

dotnet add package Microsoft.AspNetCore.App --version 2.2.8

the Minimal API:

Microsoft.AspNetCore.Builder.WebApplication app = Microsoft.AspNetCore.Builder.WebApplication.Create(new string[] { });
app.MapGet("/", () => "Hello World!");
app.RunAsync();

Ok, now you can 4 open http:localhost:5000 to look Hello World!

Because few people will use parameters in WinForm, string[] args is omitted here, and new string[] { } is used instead


If you want to ues controller, like 3 ASP.NET Core, then you can use this:

var builder = Microsoft.AspNetCore.Builder.WebApplication.CreateBuilder(new string[]{});
builder.Services.AddControllers();

var app = builder.Build();
app.MapControllers();
app.RunAsync();

HomeController.cs

using Microsoft.AspNetCore.Mvc;

namespace RuyutWinFormsApi;

[Route("api/[controller]")]
[ApiController]
public class HomeController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        return Ok("This is a test api");
    }
}

you 2 can open http://localhost:5000/api/home to look This is a test api

BTY, if you want to change 1 port, you can add this:

app.Urls.Add("http://0.0.0.0:8080");

More Related questions