OWIN 自宿主模式WebApi项目,WebApi层作为单独类库供OWIN调用
OWIN是Open Web Server Interface for .NET的首字母缩写,他的定义如下:
为什么我们需要OWIN
![](http://images2015.cnblogs.com/blog/998608/201706/998608-20170602175427946-1783463646.png)
OWIN.WebApi WebApi层
OWIN.WebApi.Sv WebApi服务层,将要作为启动项!
![](http://images2015.cnblogs.com/blog/998608/201706/998608-20170602180820227-1268649929.png)
![](http://images2015.cnblogs.com/blog/998608/201706/998608-20170602180926180-1139031854.png)
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里面的类,请对照上述两段代码进行查找。
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调用的更多相关文章
- webapi从入门到放弃(一)OWIN 自寄宿模式
1.创建web空项目 2.创建完如图 3.安装如下程序包Microsoft.AspNet.WebApi.Core (5.2.4)Microsoft.Owin.Host.SystemWeb (4.0. ...
- .Net Core3.0 WebApi 项目框架搭建 五:仓储模式
.Net Core3.0 WebApi 项目框架搭建:目录 理论介绍 仓储(Respository)是存在于工作单元和数据库之间单独分离出来的一层,是对数据访问的封装.其优点: 1)业务层不需要知道它 ...
- .Net Core3.0 WebApi 项目框架搭建 五: 轻量型ORM+异步泛型仓储
.Net Core3.0 WebApi 项目框架搭建:目录 SqlSugar介绍 SqlSugar是国人开发者开发的一款基于.NET的ORM框架,是可以运行在.NET 4.+ & .NET C ...
- Restful WebApi项目开发实践
前言 踩过了一段时间的坑,现总结一下,与大家分享,愿与大家一起讨论. Restful WebApi特点 WebApi相较于Asp.Net MVC/WebForm开发的特点就是前后端完全分离,后端使用W ...
- Asp.net WebApi 项目示例(增删改查)
1.WebApi是什么 ASP.NET Web API 是一种框架,用于轻松构建可以由多种客户端(包括浏览器和移动设备)访问的 HTTP 服务.ASP.NET Web API 是一种用于在 .NET ...
- Angularjs,WebAPI 搭建一个简易权限管理系统 —— WebAPI项目主体结构(四)
目录 前言 Angularjs名词与概念 Angularjs 基本功能演示 系统业务与实现 WebAPI项目主体结构 Angularjs 前端主体结构 5.0 WebAPI项目主体结构 5.1 总体结 ...
- SNF快速开发平台MVC-EasyUI3.9之-WebApi和MVC-controller层接收的json字符串的取值方法和调用后台服务方法
最近项目组很多人问我,从前台页面传到后台controller控制层或者WebApi 时如何取值和运算操作. 今天就都大家一个在框架内一个取值技巧 前台JS调用代码: 1.下面是选中一行数据后右键点击时 ...
- c#搭建webapi项目
一.添加WebApi项目 二.nuget下载WebApi所需的类库引用 install-package Microsoft.AspNet.WebApi install-package Micr ...
- .Net Core3.0 WebApi 项目框架搭建:目录
一.目录 .Net Core3.0 WebApi 项目框架搭建 一:实现简单的Resful Api .Net Core3.0 WebApi 项目框架搭建 二:API 文档神器 Swagger .Net ...
随机推荐
- sencha touch 总结
Ext.define("CM.product.MainviewListModel", { extend: "Ext.data.Model", config: { ...
- gulp基于seaJs模块化项目打包实践【原创】
公司还一直在延续使用jq+seajs的技术栈,所以只能基于现在的技术栈进行静态文件打包,而众所周知seajs的打包比较"偏门",在查了不少的文档和技术分享后终于琢磨出了自己的打包策 ...
- c++中关于值对象与其指针以及const值对象与其指针的问题详细介绍
话不多说,先附上一段代码与运行截图 //1 const int a = 10; //const 值对象 int *ap = (int *)&a;//将const int*指针强制转化为int* ...
- JavaEE开发之SpringMVC中的自定义拦截器及异常处理
上篇博客我们聊了<JavaEE开发之SpringMVC中的路由配置及参数传递详解>,本篇博客我们就聊一下自定义拦截器的实现.以及使用ModelAndView对象将Controller的值加 ...
- 初学strurs基础
Struts2基础学习总结 Struts 2是在WebWork2基础发展而来的. 注意:struts 2和struts 1在代码风格上几乎不一样. Struts 2 相比Struts 1的优点: 1. ...
- python库安装(numpy+scipy+matplotlib+scikit_learn)
python安装好后,库安装走了很多弯路,查了很多资料,终于安装成功,并且保存了该文章的地址,分享给大家 本人电脑windows 7,64位系统,安装的Python是3.5的,因此下载的库也是对应版本 ...
- sass入门学习篇(一)
先简单的介绍一下sass,如果你了解less,sass就没什么太大问题 Sass 是对 CSS 的扩展,让 CSS 语言更强大.优雅. 它允许你使用变量.嵌套规则. mixins.导入等众多功能, 并 ...
- css grid学习材料整理
2017-04-18 19:59:02 由浅入深: 什么是网格布局:http://www.w3cplus.com/css3/what-is-css-grid-layout.html 浏览器如何开启网格 ...
- hdu1166树状数组
C国的死对头A国这段时间正在进行军事演习,所以C国间谍头子Derek和他手下Tidy又开始忙乎了.A国在海岸线沿直线布置了N个工兵营地,Derek和Tidy的任务就是要监视这些工兵营地的活动情况.由于 ...
- Reactjs vs. Vuejs
欢迎大家关注腾讯云技术社区-博客园官方主页,我们将持续在博客园为大家推荐技术精品文章哦~ 纪俊,从事Web前端开发工作,2016年加入腾讯OMG广告平台产品部,喜欢研究前端技术框架. 这里要讨论的话题 ...