WebApi 的三种寄宿方式 (一) - 宿主和控制器在一个程序集

 

最近逛博客园,看到了Owin,学习了一下,做个笔记,说不定将来哪天就用上了

关于 Owin 的介绍,百度解释的很清楚了: https://baike.baidu.com/item/owin/2860765?fr=aladdin

参考资料:http://www.cnblogs.com/xiangchangdong/p/6768316.html#3946065

 

WebApi编译后,其实就是一个dll文件,并不是一个可执行文件,所以它需要一个宿主.

我所知道的,webapi一共有三种宿主:

1. IIS

2. SelfHost

3. OwinSelfHost

SelfHost:

1.新建控制台程序,非常干净,啥也没有

2.引入nuget包

对比 IIS 宿主可以发现不同点:

IIS:

SelfHost:

3.编辑控制台代码

        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:9527");
            config.Routes.MapHttpRoute(
                "API Default",
                "api/{controller}/{action}/{id}",
                new { id = RouteParameter.Optional });

            using (var server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("请开始您的表演");
                Console.ReadLine();
            }
        }
View Code

4.新建一个控制器

    public class TestController : ApiController
    {
        public string Get()
        {
            return "hello world";
        }
    }
View Code

5.用 Postman 测试

 

 

6.最终一览:

 

OwinSelfHost:

1.新建控制台程序:OwinSelfHost

2.引入nuget包:

注意与 SelfHost  包名的区别:

3.添加 Owin 启动类:

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{Controller}/{action}/{id}",
                defaults: new
                {
                    id = RouteParameter.Optional
                });

            app.UseWebApi(config);
        }
    }
View Code

4.新建一个控制器

    public class TestController : ApiController
    {
        public string Get()
        {
            return "this is OwinSelfHost";
        }
    }
View Code

5.控制台代码:

 static void Main(string[] args)
        {
            string baseAddress = "http://localhost:9527/";
            using (WebApp.Start(url: baseAddress))
            {
                Console.WriteLine("请开始您的表演");
                Console.ReadLine();
            }
        }
View Code

6.测试:

 

7.最终一览:

 

总结:

上面两个例子,控制器和宿主都在一个程序集,

但实际工作中,程序集应该会是一个单独的类库,

下一篇接着记录.

转载于:https://www.cnblogs.com/refuge/p/8759836.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值