.netcore windows app启动webserver

创建controller:

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

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;
    }
}

启动选项:

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启动|停止:

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配置

<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<PublishSingleFile>true</PublishSingleFile>
<IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
<!--<PublishTrimmed>true</PublishTrimmed>-->

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

闪耀星星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值