.netcore windows app启动webserver

2023-11-15

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

 

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

.netcore windows app启动webserver 的相关文章

随机推荐

  • python报错AttributeError module ‘scipy.misc‘ has no attribute ‘imresize‘和 ‘imread‘

    python报错AttributeError module scipy misc has no attribute imresize 和 imread 报错原因 scipy版本过高 解决方案 降低scipy版本 如下 pip install
  • 迁移学习之resnet50——解决过拟合及验证集上准确率上不去问题

    keras之resnet50迁移学习做分类 问题1描述 迁移学习用resnet50做分类 验证集上的准确率一直是一个大问题 有时候稳定在一个低的准确率 我的一次是一直在75 上下波动 问题2描述 resnet50迁移学习 训练集上的准确率一
  • IDEA使用jsp可以访问页面,转换为html弹出页面为404

    这种办法为绕过controller直接访问静态页面 大家只要路径对 在springmvc xml中配置好一个 标签即可
  • 【mysql】mysql 常用建表语句

    1 建立员工档案表 要求字段 员工员工编号 员工姓名 性别 工资 email 入职时间 部门 2 合理选择数据类型及字段修饰符 要求有NOT NULL auto increment primary key等 make by kakane D
  • arcgis10.2破解版下载及其详细教程;;;附带10.1-10.6的破解版,没有教程

    1 arcgis10 2破解版 https blog csdn net bigemap article details 81131840 2 arcgis10 1 10 5破解版安装包 https blog csdn net e wsq a
  • 【c++】8.map和vector容器查找、删除指定元素、emplace、insert

    1 查找与删除 vector 和 map 容器中指定元素 vector 查找或删除vector的指定元素 123 方法1 使用迭代器 不同于map map有find方法 vector本身没有find这一方法 std vector
  • 从浅到深理解bert

    更多查看https github com B C WANG AI Storage 4 2 4 2从浅到深理解bert 4 2 1 理解Attention 参考https www cnblogs com robert dlut p 86382
  • Pytorch save_image和make_grid函数详解

    Pytorch save image和make grid函数详解 make grid用于把几个图像按照网格排列的方式绘制出来 save image用于保存图像 这两个函数的函数签名差不多 所以只说一个 def make grid tenso
  • excel python插件_再见 VBA!神器工具统一 Excel 和 Python

    大家好 我是东哥 经常给大家推荐好用的数据分析工具 也收到了铁子们的各种好评 这次也不例外 我要再推荐一个 而且是个爆款神器 Excel和Jupyter Notebok都是我每天必用的工具 而且两个工具经常协同工作 一直以来工作效率也还算不
  • 线段树模板

    线段树属于高级数据结构 本文粗略地讲解了一下线段树的模板 大家直接拿去用就好 long long ls int x return x lt lt 1 long long rs int x return x lt lt 1 1 const i
  • 电感选型计算

    转载 https www richtek com Design 20Support Technical 20Document AN053 电感之种类与其特性分析 摘要 电感器是开关转换器中非常重要的元器件 如用于储能及功率滤波器 电感器的种
  • react render中进行if判断

    在render中进行if条件判断然后加载相应的模块进行渲染方法如下 第一种 第二种
  • Spark的DataFrame和Schema详解和实战案例Demo

    1 概念介绍 Spark是一个分布式计算框架 用于处理大规模数据处理任务 在Spark中 DataFrame是一种分布式的数据集合 类似于关系型数据库中的表格 DataFrame提供了一种更高级别的抽象 允许用户以声明式的方式处理数据 而不
  • 【数据分析之道-NumPy(四)】numpy广播机制

    文章目录 专栏导读 1 广播机制 2 一维数组和二维数组的广播 3 二维数组和三维数组的广播 4 标量和数组的广播 5 形状不兼容的数组不能进行广播 专栏导读 作者简介 i阿极 CSDN Python领域新星创作者 专注于分享python领
  • 小游戏:红色警戒争霸战!

    这个是当年自己在学校里面写的小游戏 现在看看好弱智啊 第一代的代码 public struct Heros public string name public double hp public double mp public double
  • a标签下载pdf文档

    开发过程中 有时我们需要点击a标签然后可以下载pdf文档 但是结果经常是pdf文档直接就在浏览器中打开了 那么想要直接下载需要怎么实现呢 实现方式 在a标签的href中写上要下载的pdf文档的地址 加上download下载属性 最后记得让后
  • Tencent://Message/协议的实现原理 .

    Tencent Message 协议的实现原理 2008年07月17日 星期四 12 04 腾讯官方通过 Tencent Message 协议可以让QQ用户显示QQ TM的在线状态发布在互联网上 并且点击 不用加好友也可以聊天 官方链接 h
  • C语言中关键字一次说清楚!!!

    目录 一 static 1 作用 2 一些例子帮助大家更深刻的理解static的几个作用 1 修饰局部变量 2 修饰全局变量和函数 二 const 1 作用 使得变量不允许被修改 提高代码的健壮性 2 本质 给编译器看的 在编译阶段起作用
  • golang 中strconv包用法

    https blog csdn net chenbaoke article details 40318357
  • .netcore windows app启动webserver

    创建controller using Microsoft AspNetCore Mvc using Microsoft Extensions Logging using System using System Collections Gen