.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>-->

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/87704.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【linux内核】DP83867添加GMII模式支持

文章目录 修改方案前期知识为什么这么修改&#xff1f;通用寄存器 修改方案 linux 4.0内核下/drivers/net/phy/dp83867.c phy_write_mmd(phydev, DP83867_DEVADDR, DP83867_CFG4, val);} if (phydev->interface PHY_INTERFACE_MODE_GMII){val phy_read_mmd(phydev, DP838…

微短剧赛道风口下的一站式点播解决方案

微短剧行业正风生水起。 一种全新的剧集模式正迅速崛起&#xff0c;并引起广泛关注。 从线下电影院的“巨幕”到PC端“网络大电影”&#xff0c;从“长视频”再到如今移动端1-3分钟的“微短剧”&#xff0c;影视行业在过去几年经历了一场深刻又显著的变化。 微短剧&#xff0…

网络丢包故障如何定位?如何解决?

引言 本期分享一个比较常见的网络问题--丢包。例如我们去ping一个网站&#xff0c;如果能ping通&#xff0c;且网站返回信息全面&#xff0c;则说明与网站服务器的通信是畅通的&#xff0c;如果ping不通&#xff0c;或者网站返回的信息不全等&#xff0c;则很可能是数据被丢包了…

Android OpenCV(七十五): 看看刚”转正“的条形码识别

前言 2021年,我们写过一篇《OpenCV 条码识别 Android 平台实践》,当时的条形码识别模块位于 opencv_contrib 仓库,但是 OpenCV 4.8.0 版本开始, 条形码识别模块已移动到 OpenCV 主仓库,至此我们无需自行编译即可轻松地调用条形码识别能力。 Bar code detector and decoder…

C++ Day3

目录 一、类 【1】类 【2】应用实例 练习&#xff1a; 【3】封装 二、this指针 【1】this指针的格式 【2】必须使用this指针的场合 三、类中的特殊成员函数 【1】构造函数 i&#xff09;功能 ii&#xff09;格式 iii&#xff09;构造函数的调用时机 iv&#xff09;…

面试官:策略模式有使用过吗?我:没有......

面试官&#xff1a;策略模式有使用过吗&#xff1f;我&#xff1a;没有… 何为策略模式&#xff1f; 比如在业务逻辑或程序设计中比如要实现某个功能&#xff0c;有多种方案可供我们选择。比如要压缩一个文件&#xff0c;我们既可以选择 ZIP 算法&#xff0c;也可以选择 GZIP…

【云计算】Docker特别版——前端一篇学会

docker学习 文章目录 一、下载安装docker&#xff08;一&#xff09;Windows桌面应用安装&#xff08;二&#xff09;Linux命令安装 二、windows注册登录docker三、Docker的常规操作(一)、基本的 Docker 命令(二)、镜像操作(三)、容器的配置(四)、登录远程仓库 四、镜像管理(一…

SIP桌面式对讲主机 井下通信广播sip寻呼话筒

SV-8003VP是我司的一款SIP桌面式对讲主机&#xff0c;具有10/100M以太网接口&#xff0c;配置了麦克风输入和扬声器输出&#xff0c;还配置多达22个按键和2.8英寸液晶显示屏&#xff0c;可以配合SIP服务器使用。SV-8003VP网路寻呼话筒可以通过麦克风或者本地线路输入对SIP终端进…

CLIP(Contrastive Language-Image Pre-training)

《Learning Transferable Visual Models From Natural Language Supervision》 从自然语言监督中学习可迁移的视觉模型 贡献:利用自然语言信号监督,打破了固定类别的范式。 方法简单,效果好。从文本中得到监督信号,引导视觉分类的任务。 它是一个 zero-shot 的视觉分类…

MyBatis进阶:告别SQL注入!MyBatis分页与特殊字符的正确使用方式

目录 引言 一、使用正确的方式实现分页 1.1.什么是分页 1.2.MyBatis中的分页实现方式 1.3.避免SQL注入的技巧 二、特殊字符的正确使用方式 2.1.什么是特殊字符 2.2.特殊字符在SQL查询中的作用 2.3.如何避免特殊字符引起的问题 2.3.1.使用CDATA区段 2.3.2.使用实体引…

AndroidStudio升级后总是Read Time Out的解决办法

AndroidStudio升级后在gradle的时候总是Time out&#xff0c;遇到过多次&#xff0c;总结一下解决办法 1、gradle下载超时 在工程目录../gradle/wrapper/gradle-wrapper.properties中找到gradle版本的下载链接&#xff0c;如下图&#xff1a; 将其复制到迅雷里下载&#xff0…

利用 XGBoost 进行时间序列预测

推荐&#xff1a;使用 NSDT场景编辑器 助你快速搭建3D应用场景 XGBoost 应用程序的常见情况是分类预测&#xff08;如欺诈检测&#xff09;或回归预测&#xff08;如房价预测&#xff09;。但是&#xff0c;也可以扩展 XGBoost 算法以预测时间序列数据。它是如何工作的&#xf…

2023 百度翻译 爬虫 js逆向 代码

js代码&#xff1a; const jsdom require("jsdom"); const {JSDOM} jsdom; const dom new JSDOM(<!DOCTYPE html><p>Hello world</p>); window dom.window; document window.document; XMLHttpRequest window.XMLHttpRequest;function n(t,…

机器学习笔记之优化算法(十六)梯度下降法在强凸函数上的收敛性证明

机器学习笔记之优化算法——梯度下降法在强凸函数上的收敛性证明 引言回顾&#xff1a;凸函数与强凸函数梯度下降法&#xff1a;凸函数上的收敛性分析 关于白老爹定理的一些新的认识梯度下降法在强凸函数上的收敛性收敛性定理介绍结论分析证明过程 引言 本节将介绍&#xff1a…

安装Node(脚手架)

目录 一&#xff0c;安装node&#xff08;脚手架&#xff09;1.1&#xff0c; 配置vue.config.js1.2&#xff0c; vue-cli3x的目录介绍1.3&#xff0c; package.json 最后 一&#xff0c;安装node&#xff08;脚手架&#xff09; 从官网直接下载安装即可&#xff0c;自带npm包管…

HBuilderX学习--运行第一个项目

HBuilderX&#xff0c;简称HX&#xff0c;是轻如编辑器、强如IDE的合体版本&#xff0c;它及轻巧、极速&#xff0c;强大的语法提示&#xff0c;提供比其他工具更优秀的vue支持大幅提升vue开发效率于一身(具体可看官方详细解释)… 一&#xff0c;HBuilderX下载安装 官网地址 …

【SVN内网穿透】远程访问Linux SVN服务

文章目录 前言1. Ubuntu安装SVN服务2. 修改配置文件2.1 修改svnserve.conf文件2.2 修改passwd文件2.3 修改authz文件 3. 启动svn服务4. 内网穿透4.1 安装cpolar内网穿透4.2 创建隧道映射本地端口 5. 测试公网访问6. 配置固定公网TCP端口地址6.1 保留一个固定的公网TCP端口地址6…

酷开科技大屏营销,锁定目标人群助力营销投放

近日&#xff0c;中科网联发布《2023年中国家庭大屏白皮书》&#xff0c;数据显示智能电视近三年内使用人群增长平稳。全国4.94亿家庭户中&#xff0c;智能大屏渗透率近九成。不仅如此&#xff0c; CCData研究预测&#xff0c;2025年中国智能电视渗透率将达到95%以上。这与三年…

stm32之16.外设定时器——TIM3

----------- 源码 void tim3_init(void) {NVIC_InitTypeDef NVIC_InitStructure;TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;//使能TIM3的硬件时钟RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);//配置TIM3的定时时间TIM_TimeBaseStructure.TIM_Period 10000-1…

基于GRU门控循环网络的时间序列预测matlab仿真,对比LSTM网络

目录 1.算法运行效果图预览 2.算法运行软件版本 3.部分核心程序 4.算法理论概述 5.算法完整程序工程 1.算法运行效果图预览 LSTM: GRU 2.算法运行软件版本 matlab2022a 3.部分核心程序 %构建GRU网络模型 layers [ ...sequenceInputLayer(N_feature)gruLayer(N_hidden)f…