winform宿主webapi

引用的Dll

添加配置文件packages.config

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.6" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.6" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi.SelfHost" version="5.2.6" targetFramework="net461" />
  <package id="Newtonsoft.Json" version="6.0.4" targetFramework="net461" />
</packages>

新建Controller文件夹里面的ValuesConntroller.cs类

 [RoutePrefix("api/values")]
    public class ValuesController : ApiController
    {
        [HttpGet]
        [Route("st")]
        public string GetServerTim(string id)
        {
            try
            {
                string result = Program.FormCheck.GetJsonById(id);

                return result;
            }
            catch
            {
                return "failed :"+ id;
            }
        }
        protected HttpRequestBase GetRequest()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_RequestContext"];//获取传统context

            HttpRequestBase request = context.Request;//定义传统request对象

            return request;
        }
        private string GetClientIp(HttpRequestMessage request = null)
        {
            request = request ?? Request;

            if (request.Properties.ContainsKey("MS_HttpContext"))
            {
                return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
            }
            else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
            {
                RemoteEndpointMessageProperty prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];
                return string.Format("Address:{0}, Port: {1}", prop.Address, prop.Port.ToString());
            }
            else if (HttpContext.Current != null)
            {
                return HttpContext.Current.Request.UserHostAddress;
            }
            else
            {
                return null;
            }
        }
    }

Program类中这样写

 public static class Program
    {
        public static CheckInterface FormCheck = null;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            FormCheck = new CheckInterface();
            Application.Run(FormCheck);
        }
    }

Form中这样写

  HttpSelfHostConfiguration config = null;
        HttpSelfHostServer server = null;
      
        public CheckInterface()
        {
            InitializeComponent();
            renderDgv_Interface.AllowUserToAddRows = false;
        }

        private void CheckInterface_Load(object sender, EventArgs e)
        {
            RefreshWebApi();
        }
        private void RefreshWebApi()
        {
            config = new HttpSelfHostConfiguration(Url);// "http://192.168.0.163:8085");
            config.Routes.MapHttpRoute("API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional });
            server = new HttpSelfHostServer(config);
            server.OpenAsync().Wait();
        }

启动之后浏览器访问http://192.168.0.163:8085/api/values?id=001即可看到weiapi接口已经成功在Winform上运行。

如果想要访问Webapi执行方法与WinformUI界面交互,用委托另外还要判断几个属性

 

  delegate void DAddRdgvData(List<JsonData> DataSourse);

        private void AddRdgvData(List<JsonData> DataSourse)
        {
            if (renderDgv_Interface.InvokeRequired)
            {
                while (!this.renderDgv_Interface.IsHandleCreated)
                {
                    if (this.renderDgv_Interface.Disposing || this.renderDgv_Interface.IsDisposed)
                        return;
                }
                DAddRdgvData d = new DAddRdgvData(AddRdgvData);
                this.renderDgv_Interface.Invoke(d, new object[] { DataSourse });
            }
            else
            {

                for (int i = 0; i < DataSourse.Count; i++)
                {
                    if (ListId.Contains(DataSourse[i].Id))
                    {
                        for (int j = 0; j < renderDgv_Interface.RowCount; j++)
                        {
                            if (renderDgv_Interface.Rows[j].Cells["rdgv_Interface_id"].Value != null)
                            {

                                if (DataSourse[i].Id.Equals(renderDgv_Interface.Rows[j].Cells["rdgv_Interface_id"].Value.ToString()))
                                {
                                    renderDgv_Interface.Rows[j].Cells["rdgv_Name"].Value = DataSourse[i].Name;
                                    renderDgv_Interface.Rows[j].Cells["rdgv_Time"].Value = DataSourse[i].Time;
                                    renderDgv_Interface.Rows[j].Cells["Rdgv_NumberTimes"].Value = DataSourse[i].Numberoftimes;
                                    renderDgv_Interface.Rows[j].Cells["rdgv_Return"].Value = DataSourse[i].CheckResult;
                                }

                            }
                        }
                    }
                    else
                    {
                       //这里向控件传数据
                    }
                }
            }
        }

  • 3
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
WinForm是一种用于创建Windows桌面应用程序的技术,而WebAPI是一种用于构建Web服务的框架。其中,WinForm主要用于创建具有图形用户界面(GUI)的桌面应用程序,而WebAPI主要用于创建基于HTTP协议的API服务。 在某些情况下,我们可能需要在WinForm应用程序中托管WebAPI。这种情况下,我们可以通过以下步骤完成: 1. 创建WinForm应用程序:首先,我们需要创建一个WinForm应用程序。这可以通过使用Visual Studio等开发工具来完成。 2. 添加WebAPI功能:接下来,我们需要添加WebAPI功能到我们的WinForm应用程序中。我们可以使用NuGet包管理器安装WebAPI相关的包,以便能够轻松地添加和使用WebAPI相关的功能。 3. 配置WebAPI路由:在使用WebAPI之前,我们需要配置WebAPI的路由。这可以通过在应用程序的启动代码中添加相关的路由配置来完成。路由配置用于将HTTP请求映射到相应的WebAPI控制器和操作方法。 4. 编写WebAPI控制器和操作方法:接下来,我们需要编写和实现相应的WebAPI控制器和操作方法。这些控制器和操作方法将用于处理WebAPI请求并返回相应的结果。 5. 启动WebAPI服务:最后,我们需要在WinForm应用程序中启动WebAPI服务。这可以通过在应用程序启动时开始监听相应的HTTP端口来完成。 通过以上步骤,我们就可以在WinForm应用程序中托管和使用WebAPI了。这样,我们就能够在桌面应用程序中提供基于HTTP协议的API服务,从而实现更多的功能和交互方式。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值