Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

c# - Hosting ASP.NET Core API in a Windows Forms Application

Background: I am working on a project that involves a WinForms app. The client wants to expose a local-only HTTP server to allow other apps to trigger functionality on a running instance of the WinForms app via a REST API (or similar). The preference is to implement the aforementioned API using ASP.NET Core.

My question is thus: How do I structure a project to have both an ASP.NET Core API and a WinForms GUI in the same process? Are there any pitfalls I'd have to be wary of?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

To 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 in the root of the project, and copy the 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 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 the project.

  9. Create ValuesController.cs in the Controllers folder and copy 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...