框架系列~OwinSelfHost自宿主的使用

在进入mvc5之后,OWIN变更很主推,很热,关于OWIN的文章也就出来了,下面阅读了dudu和一些园友的文章,自己也做了一个SelfHost的程序,测试了一下,感觉还是比较有Core的风格,可能也是面向多平台部署考虑的吧!

OWIN的英文全称是Open Web Interface for .NET。

如果仅从名称上解析,可以得出这样的信息:OWIN是针对.NET平台的开放Web接口。

那Web接口是谁和谁之间的接口呢?是Web应用程序与Web服务器之间的接口,OWIN就是.NET Web应用程序与Web服务器之间的接口。

大叔喜欢的一句话:OWIN将多种应用框架使用统一的接口来实现各框架之间的适配!

下面是WEB测试DEMO的一段代码,它可以添加多种登陆的策略

DUDU文章:http://www.cnblogs.com/dudu/p/what-is-owin.html

安装OWIN自宿主的包包

Install-Package Microsoft.AspNet.WebApi.OwinSelfHost

添加startup这个类,主要为应用程序的入口

    /// <summary>
    /// OWIN应用程序入口
    /// </summary>
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {

            HttpConfiguration config = new HttpConfiguration();

            config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
            );
            //将默认xml返回数据格式改为json
            config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            config.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("datatype", "json", "application/json"));

            app.UseWebApi(config);
            // 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888

        }
    }

添加几个测试用的Controller,其实就是webapi或者webmvc里的controller,这里以webapi为例,来说一下。

   public class HomeController : ApiController
    {
        public object Get()
        {
            return new { code = 1, msg = "OK HomeController" };
        }
    }
    public class VideoController : ApiController
    {
        public object Get()
        {
            return new { code = 2, msg = "OK VideoController" };
        }
    }

添加主程序的入口,在入口中我们将添加startup的注入点,让Owin为我们启动这个startup!

     string baseAddress = "http://192.168.2.71:9000/";
     Microsoft.Owin.Hosting.WebApp.Start<Startup>(url: baseAddress);
     Console.WriteLine("程序已启动,按任意键退出");
     Console.ReadLine();

下面我们打开浏览器,访问一下URL即可看到时结果了

 

posted @ 2017-04-21 15:59  张占岭  阅读(5048)  评论(2编辑  收藏  举报