业务场景:

公司的容器程序需要给前端暴露接口但是代码里面又不想写webapi项目工程就用到了宿主可以达到webapi的效果

1、owin实现

2、其他实现

测试实现如下

1、新建一个控制台程序

2、新建一个Controller文件并继承ApiController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http; namespace ConsoleApplication1
{
public class BlahController : ApiController
{
[HttpGet]
public string Date()
{
return DateTime.Today.ToString("yyyy/MM/dd");
}
}
}

3、实现调用

3.1实现调用一

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.SelfHost; namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
#region http://localhost:9001/Blah/Date
//指定URL
var config = new HttpSelfHostConfiguration("http://localhost:9001");
//设定路由
config.Routes.MapHttpRoute("API", "{controller}/{action}/{id}", new { id = RouteParameter.Optional });
using (var httpServer = new HttpSelfHostServer(config))
{
//OpenAsync()屬非同步呼叫,加上Wait()則等待開啟完成才往下執行
httpServer.OpenAsync().Wait();
Console.WriteLine("Web API host started...");
string line = null;
do
{
line = Console.ReadLine();
}
while (line != "exit");
//結束链接
httpServer.CloseAsync().Wait();
}
#endregion }
}
}

3.2实现调用二

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.SelfHost; namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
#region http://localhost:9001/api/Blah/Date
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration("http://localhost:9001");
config.Routes.MapHttpRoute(
name: "API",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
Console.WriteLine("Web API is started now");
Console.ReadLine();
}
#endregion
}
}
}

最新文章

  1. 记录软件工程课程项目开发时遇到的各种小问题(django)
  2. 2017年1月1日 星期日 --出埃及记 Exodus 21:27
  3. CSS之cssText
  4. iOS:交换Button中图片与文字的左右位置
  5. Osmocom-BB多信道修改代码相关
  6. linux下securetty文件
  7. PyQt4环境搭建与使用
  8. Powershell变量的幕后管理
  9. 【LeetCode练习题】Reverse Words in a String
  10. Axure快捷键大全 Axure RP Pro 6.5快捷键
  11. Android中ListView下拉刷新的实现
  12. Appium-desktop安装与使用
  13. First:安装配置JDK and 部署Tomcat
  14. windows配置ssh免密登录linux
  15. java遍历Map
  16. 06_Hadoop分布式文件系统HDFS架构讲解
  17. 【转】Java学习---Java的锁和Mysql的锁机制
  18. 用NI的数据采集卡实现简单电子测试之4——半导体温度传感器
  19. BZOJ4543 Hotel加强版
  20. JavaScript匿名函数知多少

热门文章

  1. CF 1278C Berry Jam 题解
  2. No module named 'widgets'
  3. 本地虚拟机搭建ES集群
  4. pygame学习的第一天
  5. Flutter 使用json_model解析json生成dart文件
  6. video-player
  7. redis api-list
  8. MySQL部分语法
  9. c++生成的动态库移到其他电脑上,动态库不能运行
  10. 七 联系人与客户多对一配置&联系人列表&分页查询联系人