.netcore windows app启动webserver

news/2024/5/19 23:24:21 标签: .netcore, windows

创建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>-->

 

 


http://www.niftyadmin.cn/n/4951141.html

相关文章

【C语言基础】宏定义的用法详解

&#x1f4e2;&#xff1a;如果你也对机器人、人工智能感兴趣&#xff0c;看来我们志同道合✨ &#x1f4e2;&#xff1a;不妨浏览一下我的博客主页【https://blog.csdn.net/weixin_51244852】 &#x1f4e2;&#xff1a;文章若有幸对你有帮助&#xff0c;可点赞 &#x1f44d;…

java四大访问修饰符

java中有四大修饰符&#xff0c;分别为private,default,protected,public,下面主要是四者之间的区别&#xff1a; private(私有的) private可以修饰成员变量&#xff0c;成员方法&#xff0c;构造方法&#xff0c;不能修饰类(此刻指的是外部类&#xff0c;内部类不加以考虑)。…

scala transient

scala transient 1. 由来 transient是Scala中的一个关键字&#xff0c;用于修饰类的成员变量。它指示编译器在序列化对象时忽略被修饰的变量。 2. 示例 以下是使用transient修饰变量的简单示例&#xff1a; import java.io._class Person(val name: String, transient pri…

从今天起,重新出发

2017年的时候&#xff0c;我还是一名在校大学生&#xff0c;当时为了准备实习面试写下了第一篇学习笔记。 2018年我开始工作&#xff0c;简单记录了使用 Airflow 的踩坑记录。 一直到今天我已经是一个工作了五年的社畜&#xff0c;但是很遗憾没有把工作中的成长记录下来。 当…

FPGA应用学习笔记----I2S和总结

时序一致在慢时序方便得多 增加了时序分布和分析的复杂性 使用fifo会开销大量资源

集成大淘客实现多个电商平台的数据互连

大淘客是一家导购优惠平台。 它通过整合多个电商平台的商品和优惠信息&#xff0c;为用户提供高品质、低价格的商品推荐和购物指南。 场景描述&#xff1a; 基于大淘客开放平台的API能力&#xff0c;零代码实现多个电商平台的导购数据、商品数据、账号销售数据和其它应用数据…

前端-Vue3-状态管理库Pinia

Pinia官网 1.状态管理库是什么&#xff1f; Store是一个保存状态和业务逻辑的实体&#xff0c;它并不与你的组件树绑定。 换句话说&#xff0c;它承载着全局的状态。它有地像一个永远存在的组件&#xff0c;每个组件都可以读取何写入它。 它有三个概念&#xff0c;state、get…