.netcore windows app启动webserver

创建controller:

cs 复制代码
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace MyWorker.Controller
{
    [ApiController]
    [Route("/api/[controller]")]
    public class HomeController
    {
        public ILogger<HomeController> logger;
        public HomeController(ILogger<HomeController> logger)
        {
            this.logger = logger;
        }

        public string Echo()
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
    }
}

定义webserver

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace MyWorker
{
    public static class WebServer
    {
        public static WorkerConfig Config
        {
            get;
            private set;
        }

        public static bool IsRunning
        {
            get { return host != null; }
        }

        private static IWebHost host;

        static WebServer()
        {
            ReadConfig();
        }

        #region 配置
        public static void ReadConfig()
        {
            string cfgFile = AppDomain.CurrentDomain.BaseDirectory + "my.json";
            try
            {
                if (File.Exists(cfgFile))
                {
                    string json = File.ReadAllText(cfgFile);
                    if (!string.IsNullOrEmpty(json))
                    {
                        Config = System.Text.Json.JsonSerializer.Deserialize<WorkerConfig>(json);
                    }
                }
            }
            catch
            {
                File.Delete(cfgFile);
            }

            if(Config == null)
            {
                Config = new WorkerConfig();
            }
        }

        public static void SaveConfig()
        {
            string cfgFile = AppDomain.CurrentDomain.BaseDirectory + "my.json";
            File.WriteAllText(cfgFile, System.Text.Json.JsonSerializer.Serialize(Config),Encoding.UTF8);

        }
        #endregion
        public static void Start()
        {
            try
            {
                host = WebHost.CreateDefaultBuilder<Startup>(FrmMain.StartArgs)
                    .UseUrls(string.Format("http://*:{0}", Config.Port)).Build();

                host.StartAsync();
            }
            catch
            {
                host = null;
                throw;
            }
        }

        public static void Stop()
        {
            if(host != null)
            {
                host.StopAsync();
                host = null;
            }
        }
    }

    public class WorkerConfig{
        public int Port { get; set; } = 8800;
    }
}

启动选项:

cs 复制代码
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Internal;

namespace MyWorker
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app)
        {
            app.UseMvc();
        }
    }
}

winform启动|停止:

cs 复制代码
namespace MyWorker
{
    public partial class FrmMain : Form
    {
        public static string[] StartArgs = null;

        bool isClose = false;

        public FrmMain(string[] args)
        {
            InitializeComponent();
            StartArgs = args;
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            StartServer();
        }

        private void FrmMain_Shown(object sender, EventArgs e)
        {

        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!isClose)
            {
                this.WindowState = FormWindowState.Minimized;
                this.ShowInTaskbar = false;
                this.Hide();
                e.Cancel = true;
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            StartServer();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            StopServer();
        }

        private void tray_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            this.ShowInTaskbar = true;
            this.Show();
            this.BringToFront();
        }

        private void tmiShowMain_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            this.ShowInTaskbar = true;
            this.Show();
            this.BringToFront();
        }

        private void tmiStop_Click(object sender, EventArgs e)
        {
            StopServer();
        }

        private void tmiExit_Click(object sender, EventArgs e)
        {
            if (WebServer.IsRunning)
            {
                if (MessageBox.Show("服务正在运行,确定退出吗?", "提示",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                {
                    return;
                }

                StopServer();
            }

            isClose = true;
            this.Close();
        }

        private void StartServer()
        {
            try
            {
                int port = Convert.ToInt32(txtPort.Value);
                if (WebServer.Config.Port != port)
                {
                    WebServer.Config.Port = port;
                    WebServer.SaveConfig();
                }
                WebServer.Start();
                btnStart.Enabled = false;
                btnStop.Enabled = true;
                tmiStop.Text = "停止(&S)";
                tmiStop.Image = imgList.Images[3];
                lblTip.Text = "服务已启动";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "启动服务");
            }
        }

        private void StopServer()
        {
            try
            {
                WebServer.Stop();
                btnStart.Enabled = true;
                btnStop.Enabled = false;
                tmiStop.Text = "启动(&S)";
                tmiStop.Image = imgList.Images[2];
                lblTip.Text = "服务已停止";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "停止服务");
            }
        }

    }
}

页面预览:

测试:

配置打包单个文件:

csproj配置

XML 复制代码
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<PublishSingleFile>true</PublishSingleFile>
<IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
<!--<PublishTrimmed>true</PublishTrimmed>-->
相关推荐
hairenjing11235 小时前
使用 Mac 数据恢复从 iPhoto 图库中恢复照片
windows·stm32·嵌入式硬件·macos·word
九鼎科技-Leo6 小时前
了解 .NET 运行时与 .NET 框架:基础概念与相互关系
windows·c#·.net
九鼎科技-Leo9 小时前
什么是 ASP.NET Core?与 ASP.NET MVC 有什么区别?
windows·后端·c#·asp.net·mvc·.net
黎明晓月13 小时前
Java之字符串分割转换List
java·windows·list
九鼎科技-Leo13 小时前
在 C# 中,ICollection 和 IList 接口有什么区别?
windows·c#·.net
时光追逐者13 小时前
C#/.NET/.NET Core学习路线集合,学习不迷路!
开发语言·学习·c#·asp.net·.net·.netcore·微软技术
顾辰呀14 小时前
实现uniapp-微信小程序 搜索框+上拉加载+下拉刷新
前端·windows
Bunny Chen16 小时前
如何缩小PPT演示文稿的大小?
windows·microsoft·powerpoint
如光照17 小时前
Linux与Windows中的流量抓取工具:wireshark与tcpdump
linux·windows·测试工具·网络安全
wwc_boke17 小时前
Linux查看端口占用及Windows查看端口占用
linux·运维·windows