webapi------宿主程序

业务场景:

公司的容器程序需要给前端暴露接口但是代码里面又不想写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
        }
    }
}

 

转载于:https://www.cnblogs.com/macT/p/11183539.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值