以下是實(shí)現(xiàn)C# Winform集成Web頁面登錄及配置修改功能的代碼方案,結(jié)合了數(shù)據(jù)庫驗(yàn)證和Web服務(wù)交互,實(shí)現(xiàn)自托管Web服務(wù)的完整方案,無需依賴IIS或其他第三方服務(wù):
一、自托管Web服務(wù)核心實(shí)現(xiàn)(OwinSelfHost)
// Startup.cs
using Owin;
using System.Web.Http;
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
app.UseWebApi(config);
}
}
// Program.cs
using Microsoft.Owin.Hosting;
using System;
class Program
{
static void Main(string[] args)
{
string baseAddress = "http://localhost:8080/";
using (WebApp.Start<Startup>(baseAddress))
{
Console.WriteLine($"Web服務(wù)已啟動(dòng):{baseAddress}");
Console.WriteLine("按任意鍵退出...");
Console.ReadKey();
}
}
}
二、Winform集成Web服務(wù)(引用)
// MainForm.cs
public partial class MainForm : Form
{
private IDisposable _webService;
public MainForm()
{
InitializeComponent();
StartWebServer();
}
private void StartWebServer()
{
try
{
_webService = WebApp.Start<Startup>("http://localhost:8080/");
btnStartServer.Enabled = false;
btnStopServer.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show($"啟動(dòng)失敗:{ex.Message}");
}
}
private void StopWebServer()
{
_webService?.Dispose();
btnStartServer.Enabled = true;
btnStopServer.Enabled = false;
}
// 配置管理示例方法
private async void btnUpdateConfig_Click(object sender, EventArgs e)
{
var config = new ConfigModel { Param1 = "新值" };
using (var client = new HttpClient())
{
var response = await client.PostAsJsonAsync("http://localhost:8080/api/config", config);
if (response.IsSuccessStatusCode)
{
MessageBox.Show("配置更新成功!");
}
}
}
}
三、Web API控制器示例
// ConfigController.cs
using System.Collections.Generic;
using System.Web.Http;
public class ConfigModel
{
public string Param1 { get; set; }
public int Param2 { get; set; }
}
public class ConfigController : ApiController
{
private static readonly List<ConfigModel> _configs = new List<ConfigModel>();
[HttpGet]
public IHttpActionResult GetConfig()
{
return Ok(_configs.FirstOrDefault());
}
[HttpPost]
public IHttpActionResult UpdateConfig(ConfigModel config)
{
_configs.Clear();
_configs.Add(config);
return Ok();
}
}
四、前端交互頁面(HTML+JavaScript)
<!-- config.html -->
<form id="configForm">
<input type="text" name="param1" placeholder="參數(shù)1">
<input type="text" name="param2" placeholder="參數(shù)2">
<button type="submit">保存</button>
</form>
<script>
document.getElementById('configForm').addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const response = await fetch('http://localhost:8080/api/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(Object.fromEntries(formData))
});
if (response.ok) alert('配置已更新!');
});
</script>
關(guān)鍵實(shí)現(xiàn)說明
自托管技術(shù)選型:
使用OwinSelfHost 實(shí)現(xiàn)輕量級(jí)Web服務(wù)托管
支持.NET Framework 4.5+和.NET 6+跨平臺(tái)部署
權(quán)限管理:
需以管理員身份運(yùn)行程序以開啟HTTP監(jiān)聽
建議通過HTTPS加密通信(需配置SSL證書)
功能擴(kuò)展建議:
添加JWT身份驗(yàn)證中間件
使用內(nèi)存數(shù)據(jù)庫(如SQLite)替代靜態(tài)存儲(chǔ)
實(shí)現(xiàn)配置變更日志記錄
部署注意事項(xiàng):
可將服務(wù)作為Windows服務(wù)運(yùn)行
建議設(shè)置防火墻規(guī)則開放80/443端口
完整代碼需根據(jù)實(shí)際項(xiàng)目結(jié)構(gòu)調(diào)整數(shù)據(jù)庫連接、路由配置等參數(shù)。建議先在開發(fā)環(huán)境測(cè)試自托管服務(wù)穩(wěn)定性,再部署到目標(biāo)機(jī)器。
該文章在 2025/3/15 16:48:13 編輯過