当前位置: 首页 > news >正文

.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);}#endregionpublic 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.lryc.cn/news/132762.html

相关文章:

  • 泰迪大数据挖掘建模平台功能特色介绍
  • 【问题】java序列化,什么时候使用
  • 【最新可用】VMware中ubuntu与主机window之间使用共享文件夹传输大文件
  • A. Two Semiknights Meet
  • 〔011〕Stable Diffusion 之 解决绘制多人或面部很小的人物时面部崩坏问题 篇
  • 在ubuntu+cpolar+rabbitMQ环境下,实现mq服务端远程访问
  • Vue elementui 实现表格selection的默认勾选,翻页记录勾选状态
  • CloudCompare——统计滤波
  • nodejs+vue古诗词在线测试管理系统
  • 174-地下城游戏
  • Linux定时任务crontab
  • golang字符串切片去重
  • git如何检查和修改忽略文件和忽略规则
  • Android AppCompatActivity标题栏操作
  • 解决conda activate报错
  • FreeMarker--表达式和运算符的用法(全面/有示例)
  • 设计模式 -- 策略模式(传统面向对象与JavaScript 的对比实现)
  • 非常详细的 Ceph 介绍、原理、架构
  • js 的正则表达式(二)
  • 星际争霸之小霸王之小蜜蜂(四)--事件监听-让小蜜蜂动起来
  • Visual Studio 2022 你必须知道的实用调试技巧
  • Webgl 存储限定符attribute、gl.getAttribLocation、gl.vertexAttrib3f及其同族函数和矢量版本的介绍
  • postgresql跨库创建视图
  • FPGA时钟
  • FifthOne:计算机视觉提示和技巧
  • Oracle19c-补丁升级报错合集(一)
  • 嵌入式:ARM Day6
  • ClickHouse安装步骤
  • Android CCodec (二十) CCodec Native服务实现分析
  • Shell编程学习之while循环语句和for循环语句的应用