WinForms 嵌入 Web服务
阅读原文时间:2023年07月08日阅读:1

1、首先安装一个Kestrel服务器包

Microsoft.AspNetCore.Server.Kestrel

2、在Main方法中插入如下代码

static class Program
{
///

/// The main entry point for the application. ///
[STAThread]
static void Main()
{
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

        var host = new WebHostBuilder()  
            .UseKestrel()  
             .Configure(ConfigureWebApp)  
            .UseContentRoot(Directory.GetCurrentDirectory())  
           .UseUrls("http://\*:5001").Build();  
        host.Run();  

        Application.Run(new Form1());  
    }

    private static void ConfigureWebApp(IApplicationBuilder app)  
    {  
        app.Run(Request);  
    }

    private static async Task Request(HttpContext context)  
    {  
        // 处理非静态请求  
        var request = context.Request;  
        var response = context.Response;  
        string path = request.Path.Value;  
        response.ContentType = "application/json; charset=UTF-8";  
        bool hasRun = true;  
        if (path == "/report")  
        {  
            string value = request.Query\["value"\];  
            response.StatusCode = 200;  
        }  
        else  
        {  
            response.StatusCode = 404;  
        }  
    }

}

3、启动窗体  在浏览器输入http://127.0.0.1:5001/report 即可调用 Request 方法中对应的逻辑