OWIN是Open Web Server Interface for .NET的首字母缩写,他的定义如下:

OWIN在.NET Web Servers与Web Application之间定义了一套标准接口,OWIN的目标是用于解耦Web Server和Web Application。基于此标准,鼓励开发者开发简单、灵活的模块,从而推进.NET Web Development开源生态系统的发展。

为什么我们需要OWIN

过去,IIS作为.NET开发者来说是最常用的Web Server(没有之一),源于微软产品的紧耦合关系,我们不得不将Website、Web Application、Web API等部署在IIS上,事实上在2010年前并没有什么不妥,但随着近些年来Web的发展,特别是移动互联网飞速发展,IIS作为Web Server已经暴露出他的不足了。主要体现在两个方面,ASP.NET (System.Web)紧耦合IIS,IIS紧耦合OS,这就意味着,我们的Web Framework必须部署在微软的操作系统上,难以跨平台。
 
...
 
OWIN是什么?在本文里面就不进行赘述,网上有很多介绍OWIN的信息以及优缺点的博文,这里可以给几个链接大家进行自行参考:
..
 
下面我们重点介绍我在搭建OWIN自宿主平台的过程,对于我是学习的过程,对于想要接触他的大家来说,也是一种帮助。
 
很多人搭建的OWIN+WebApi项目都是写在一个项目中的,我个人为了代码的隔离,将控制器层写在了另外一个项目中,这样有助于后期大型框架的形成。
下面是搭建步骤:
1、首先新建一个控制台应用程序和一个.NETFramework类库项目,控制台引用类库项目。
项目结构如下图所示:

OWIN.WebApi WebApi层

OWIN.WebApi.Sv WebApi服务层,将要作为启动项!

2、控制台项目使用NuGet引用需要的类库:
  OWIN
  Microsoft.Owin.Hosting
  Microsoft.Owin.Host.HttpListener
  Microsoct.AspNet.WebApi.Owin
  这里需要手动从WebApi项目里面找到System.Web.Web,System.Net.Http等Web类库进行引用。
  OWIN.WebApi.Srv层的引用情况(我这里有跨域配置,不需要的请忽略)
  
  在OWIN.WebApi层,我们需要同样引用Web的类库,我们才可以在WebApi项目控制器层继承自ApiController
    OWIN.WebApi层的引用情况(我这里有跨域配置,不需要的请忽略)
  
 3、因为WebApi层要分开类库项目写,所以这里比一般的OWIN要多一些配置,在我项目的OWIN.WebApi层的config目录下,我新建了一个Global.cs类,里面的代码是对控制器的解析,代码展示如下:
 using System.Web.Http;
 using System.Web.Http.Dispatcher;
 using System;
 using System.Collections.Concurrent;
 using System.Collections.Generic;
 using System.Linq;
 using System.Net;
 using System.Net.Http;
 using System.Web.Http.Controllers;

 namespace OWIN.WebApi.config
 {
     public class WebApiApplication : System.Web.HttpApplication
     {
         protected void Application_Start()
         {
             //ignore the xml return it`s setting let json return only
             GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
             GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

             GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector),
             new WebApiControllerSelector(GlobalConfiguration.Configuration));
         }
     }
     /// <summary>
     /// the WebApiControllerSelector
     /// author:qixiao
     /// time:2017-1-31 19:24:32
     /// </summary>
     public class WebApiControllerSelector : DefaultHttpControllerSelector
     {
         private const string NamespaceRouteVariableName = "Namespace";
         private readonly HttpConfiguration _configuration;
         private readonly Lazy<ConcurrentDictionary<string, Type>> _apiControllerCache;

         public WebApiControllerSelector(HttpConfiguration configuration)
             : base(configuration)
         {
             _configuration = configuration;
             _apiControllerCache = new Lazy<ConcurrentDictionary<string, Type>>(
                 new Func<ConcurrentDictionary<string, Type>>(InitializeApiControllerCache));
         }

         private ConcurrentDictionary<string, Type> InitializeApiControllerCache()
         {
             IAssembliesResolver assembliesResolver = this._configuration.Services.GetAssembliesResolver();
             var types = this._configuration.Services.GetHttpControllerTypeResolver()
                 .GetControllerTypes(assembliesResolver).ToDictionary(t => t.FullName, t => t);

             return new ConcurrentDictionary<string, Type>(types);
         }

         public IEnumerable<string> GetControllerFullName(HttpRequestMessage request, string controllerName)
         {
             object namespaceName;
             var data = request.GetRouteData();
             IEnumerable<string> keys = _apiControllerCache.Value.ToDictionary<KeyValuePair<string, Type>, string, Type>(t => t.Key,
                     t => t.Value, StringComparer.CurrentCultureIgnoreCase).Keys.ToList();

             if (!data.Values.TryGetValue(NamespaceRouteVariableName, out namespaceName))
             {
                 return from k in keys
                        where k.EndsWith(string.Format(".{0}{1}", controllerName,
                        DefaultHttpControllerSelector.ControllerSuffix), StringComparison.CurrentCultureIgnoreCase)
                        select k;
             }

             string[] namespaces = (string[])namespaceName;
             return from n in namespaces
                    join k in keys on string.Format("{0}.{1}{2}", n, controllerName,
                    DefaultHttpControllerSelector.ControllerSuffix).ToLower() equals k.ToLower()
                    select k;
         }

         public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
         {
             Type type;
             if (request == null)
             {
                 throw new ArgumentNullException("request");
             }
             string controllerName = this.GetControllerName(request);
             if (string.IsNullOrEmpty(controllerName))
             {
                 throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound,
                     string.Format("No route providing a controller name was found to match request URI '{0}'", new object[] { request.RequestUri })));
             }
             IEnumerable<string> fullNames = GetControllerFullName(request, controllerName);
             )
             {
                 throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound,
                         string.Format("No route providing a controller name was found to match request URI '{0}'", new object[] { request.RequestUri })));
             }

             if (this._apiControllerCache.Value.TryGetValue(fullNames.First(), out type))
             {
                 return new HttpControllerDescriptor(_configuration, controllerName, type);
             }
             throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound,
                 string.Format("No route providing a controller name was found to match request URI '{0}'", new object[] { request.RequestUri })));
         }
     }
 }

4、在OWIN.WebApi.Srv层里面新建AppStart.cs类,并且写如下代码:

 using Microsoft.Owin.Hosting;
 using System;
 using Owin;
 using System.Web.Http;
 using System.Web.Http.Dispatcher;
 using QX_Frame.App.WebApi.Extends;
 using System.Web.Http.Cors;

 namespace OWIN.WebApi.Srv
 {
     class AppStart
     {
         static void Main(string[] args)
         {
             //string baseAddress = "http://localhost:3999/";    //localhost visit
             string baseAddress = "http://+:3999/";              //all internet environment visit
             try
             {
                 WebApp.Start<StartUp>(url: baseAddress);
                 Console.WriteLine("BaseIpAddress is " + baseAddress);
                 Console.WriteLine("\nApplication Started !");
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.ToString());
             }

             for (;;)
             {
                 Console.ReadLine();
             }
         }
     }
     //the start up configuration
     class StartUp
     {
         public void Configuration(IAppBuilder appBuilder)
         {
             HttpConfiguration config = new HttpConfiguration();

             // Web API configuration and services
             //跨域配置 //need reference from nuget
             config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
             //enabing attribute routing
             config.MapHttpAttributeRoutes();
             // Web API Convention-based routing.
             config.Routes.MapHttpRoute(
                 name: "DefaultApi",
                 routeTemplate: "api/{controller}/{id}",
                 defaults: new { id = RouteParameter.Optional },
                 namespaces: new string[] { "OWIN.WebApi" }
             );
             config.Services.Replace(typeof(IHttpControllerSelector), new OWIN.WebApi.config.WebApiControllerSelector(config));

             //if config the global filter input there need not write the attributes
             //config.Filters.Add(new App.Web.Filters.ExceptionAttribute_DG());

             //new ClassRegisters(); //register ioc menbers

             appBuilder.UseWebApi(config);
         }
     }
 }

里面对地址进行了配置,当然可以根据需求自行配置,显示信息也进行了适当的展示,需要说明的一点是,我这里进行了跨域的配置,没有配置或者是不需要的请注释掉并忽略!

这里需要注意的是第53行,这里引用的是刚才的OWIN.WebApi层的Global.cs里面的类,请对照上述两段代码进行查找。

这行是关键,有了这行,程序才可以扫描到WebApi层的Controller。好了,我们进行Controller的书写。
5、在OWIN.WebApi层进行控制器类的编写,这里随意,我只在这里列出我的例子。
 using QX_Frame.App.WebApi;
 using QX_Frame.Helper_DG;
 using System.Web.Http;

 namespace OWIN.WebApi
 {
     /*
      * author:qixiao
      * time:2017-2-27 10:32:57
      **/
     public class Test1Controller:ApiController
     {
         //access http://localhost:3999/api/Test1  get method
         public IHttpActionResult GetTest()
         {
             //throw new Exception_DG("login id , pwd", "argumets can not be null", 11111, 2222);
             return Json(new { IsSuccess = true, Msg = "this is get method" });
         }
         //access http://localhost:3999/api/Test1  post method
         public IHttpActionResult PostTest(dynamic queryData)
         {
             return Json(new { IsSuccess = true, Msg = "this is post method",Data=queryData });
         }
         //access http://localhost:3999/api/Test1  put method
         public IHttpActionResult PutTest()
         {
             return Json(new { IsSuccess = true, Msg = "this is put method" });
         }
         //access http://localhost:3999/api/Test1  delete method
         public IHttpActionResult DeleteTest()
         {
             return Json(new { IsSuccess = true, Msg = "this is delete method" });
         }
     }
 }

这里我是用的是RESTFull风格的WebApi控制器接口。

然后我们可以进行试运行:

服务启动成功!

测试通过,我们可以尽情地探索后续开发步骤!

OWIN 自宿主模式WebApi项目,WebApi层作为单独类库供OWIN调用的更多相关文章

  1. webapi从入门到放弃(一)OWIN 自寄宿模式

     1.创建web空项目 2.创建完如图 3.安装如下程序包Microsoft.AspNet.WebApi.Core (5.2.4)Microsoft.Owin.Host.SystemWeb (4.0. ...

  2. .Net Core3.0 WebApi 项目框架搭建 五:仓储模式

    .Net Core3.0 WebApi 项目框架搭建:目录 理论介绍 仓储(Respository)是存在于工作单元和数据库之间单独分离出来的一层,是对数据访问的封装.其优点: 1)业务层不需要知道它 ...

  3. .Net Core3.0 WebApi 项目框架搭建 五: 轻量型ORM+异步泛型仓储

    .Net Core3.0 WebApi 项目框架搭建:目录 SqlSugar介绍 SqlSugar是国人开发者开发的一款基于.NET的ORM框架,是可以运行在.NET 4.+ & .NET C ...

  4. Restful WebApi项目开发实践

    前言 踩过了一段时间的坑,现总结一下,与大家分享,愿与大家一起讨论. Restful WebApi特点 WebApi相较于Asp.Net MVC/WebForm开发的特点就是前后端完全分离,后端使用W ...

  5. Asp.net WebApi 项目示例(增删改查)

    1.WebApi是什么 ASP.NET Web API 是一种框架,用于轻松构建可以由多种客户端(包括浏览器和移动设备)访问的 HTTP 服务.ASP.NET Web API 是一种用于在 .NET ...

  6. Angularjs,WebAPI 搭建一个简易权限管理系统 —— WebAPI项目主体结构(四)

    目录 前言 Angularjs名词与概念 Angularjs 基本功能演示 系统业务与实现 WebAPI项目主体结构 Angularjs 前端主体结构 5.0 WebAPI项目主体结构 5.1 总体结 ...

  7. SNF快速开发平台MVC-EasyUI3.9之-WebApi和MVC-controller层接收的json字符串的取值方法和调用后台服务方法

    最近项目组很多人问我,从前台页面传到后台controller控制层或者WebApi 时如何取值和运算操作. 今天就都大家一个在框架内一个取值技巧 前台JS调用代码: 1.下面是选中一行数据后右键点击时 ...

  8. c#搭建webapi项目

    一.添加WebApi项目     二.nuget下载WebApi所需的类库引用 install-package Microsoft.AspNet.WebApi install-package Micr ...

  9. .Net Core3.0 WebApi 项目框架搭建:目录

    一.目录 .Net Core3.0 WebApi 项目框架搭建 一:实现简单的Resful Api .Net Core3.0 WebApi 项目框架搭建 二:API 文档神器 Swagger .Net ...

随机推荐

  1. Spring Boot 学习笔记--整合Thymeleaf

    1.新建Spring Boot项目 添加spring-boot-starter-thymeleaf依赖 <dependency> <groupId>org.springfram ...

  2. C字符串输入输出函数

    下面就几个常用的字符串输入输出函数做个小小的总结TAT 使用时添加头文件:#include<stdio.h>. scanf("格式控制字符串",变量地址列表):(pri ...

  3. 浅谈C#数组(二)

    六.枚举集合 在foreach语句中使用枚举,可以迭代集合中的元素,且无需知道集合中元素的个数.foreach语句使用一个枚举器.foreach会调用实现了IEnumerable接口的集合类中的Get ...

  4. VS2003"无法启动调试 没有正确安装调试器"的解决方法

    在用VS2003做项目的时候,经常调试程序,但是有时候回出现如下问题“无法启动调试,没有正确安装调试器,请运行安装程序或修复调试器”.第一次碰到还以为是运气不好,就重新用vs2003安装程序重新修复了 ...

  5. 转 JSON与XML转换

    这两天处理模块的联调工作,在json与XML转换中出现了一些奇怪的问题,仔细究来,实为对org.json.*包知之太少.晚上baidu.google一下,找出了问题出现的原因.在模块中,使用了两个方法 ...

  6. Ionic2 + Angular4 + JSSDK开发中的若干问题汇总

    前景 目前微信公众号程序开发已经相当火热,客户要求自己的系统有一个公众号,已经是一个很常见的需要. 使用公众号可以很方便的便于项目干系人查看信息和进行互动,还可以很方便录入一些电脑端不便于录入的数据, ...

  7. jQuery的hover方法搭配css的hover选择器,实现选中元素突出显示

    问题简述: 今天做帮一个师姐做网页遇到一个这样的要求: 鼠标不移动进表格,表格透明度不变. 鼠标移动进表格,hover到的单元格透明度不变,没hover到的单元格透明度改变. 先贴我已经实现好的效果, ...

  8. 进击 spring !!

    1.spring简介 Spring 是一个开源框架,是为了解决企业应用程序开发复杂性而创建的.框架的主要优势之一就是其分层架构,分层架构允许您选择使用某一个组件,同时为 J2EE 应用程序开发提供集成 ...

  9. php 中时间函数date及常用的时间计算

    曾在项目中需要使用到今天,昨天,本周,本月,本季度,今年,上周上月,上季度等等时间戳,趁最近时间比较充足,因此计划对php的相关时间知识点进行总结学习 1,阅读php手册date函数 常用时间函数: ...

  10. 从Python小白到第一个小游戏发布

    1.安装必要的环境(附图两张) 直接下载安装程序,本人win10系统,根据电脑系统下载并安装对应的python.exe,安装路径可以选择D盘的,具体安装细节这里就不说了,不知道的可以留言或者找度娘 2 ...