c# 实现网页(Web Page)和本地程序(Local App)之间的动态调用

场景说明:例如使用网站时,需要通过第三方程序获取本机的串口获取信息,服务端无法直接获取,需要通过本地程序

解决方案:通过本地exe程序通过监听http请求的特定端口,然后实现在本地exe调用第三方程序

第三方程序例如:DLL插件,用于调用电脑本地硬件(打印机、扫描仪、读卡器等)或者通过DLL插件和第三方项目程序进行交互。

                             Exe可执行程序,主要用于集成第三方程序。

主要实现逻辑(参考:https://github.com/wrxiang/WebRunLocal)

using System;
using System.Net.Http;
using System.ServiceModel;
using System.Web.Http;
using System.Web.Http.SelfHost;

namespace RestController
{
    class Program
    {
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:12357");
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}");
            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
        }
    }

    public class TestController : ApiController
    {
        [HttpPost]
        public HttpResponseMessage PostMethodFactory()
        {
            return new HttpResponseMessage();
        }
    }
}

  

posted @ 2022-12-15 15:57  Tozhang  阅读(476)  评论(0编辑  收藏  举报