使用owin不依赖iis 构建自承载的c# web服务器,支持ajax+html+webapi

前端之家收集整理的这篇文章主要介绍了使用owin不依赖iis 构建自承载的c# web服务器,支持ajax+html+webapi前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

最近试用了一下 RavenDb 数据,该数据库是一种 nosql 数据库。底层使用 lucene.net 做为数据库文件

觉得更有意思的是他的 web管理工具,居然绕过了iis 而是使用一个 windows服务承载的一个网站。


所以研究了一下,原来它用的是 owin 技术。

但是在mvc4 以前 ,暂时不能承载 webform 、mvc 的网站,原因是webform 、mvc 对 iis 的耦合度太高。因为他们引用了 system.web.dll 组件。

该组件依赖 iis。

期待 mvc 后续版本不再依赖 system.web.dll ~~~~~


开始构建web服务器,下面只复制了一些关键部分的 代码

实例程序可以去我的资源中下载

下载地址:http://download.csdn.net/detail/xxj_jing/9583113


控制台程序

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. //监听地址
  6. string baseAddress = string.Format("http://{0}:{1}/",System.Configuration.ConfigurationManager.AppSettings.Get("Domain"),System.Configuration.ConfigurationManager.AppSettings.Get("Port"));
  7.  
  8. //启动监听
  9. using (WebApp.Start<Startup>(url: baseAddress))
  10. {
  11. Console.WriteLine("host 已启动:{0}",DateTime.Now);
  12. Console.WriteLine("访问:{0}/page/index.html",baseAddress);
  13. Console.ReadLine();
  14. }
  15. }
  16.  
  17. }

Startup 请求处理程序(WebApp.Start<T>() 方法自动执行 T.Configuration() 方法
  1. using System.IO;
  2. using System.Net.Http.Formatting;
  3. using Owin;
  4. using Microsoft.Owin;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Web.Http;
  10.  
  11. namespace OwinSelfhostSample
  12. {
  13. class Startup
  14. {
  15.  
  16. private static string _siteDir = System.Configuration.ConfigurationManager.AppSettings.Get("SiteDir");
  17. // This code configures Web API. The Startup class is specified as a type
  18. // parameter in the WebApp.Start method.
  19. public void Configuration(IAppBuilder app)
  20. {
  21. // web api 接口
  22. HttpConfiguration config = InitWebApiConfig();
  23. app.UseWebApi(config);
  24.  
  25. //静态文件托管
  26. app.Use((context,fun) =>
  27. {
  28. return myhandle(context,fun);
  29. });
  30. }
  31. /// <summary>
  32. /// 路由初始化
  33. /// </summary>
  34. public HttpConfiguration InitWebApiConfig()
  35. {
  36.  
  37. HttpConfiguration config = new HttpConfiguration();
  38. config.Routes.MapHttpRoute(
  39. name: "Default",routeTemplate: "api/{controller}/{action}",defaults: new { id = RouteParameter.Optional }
  40. );
  41. config.Formatters
  42. .XmlFormatter.SupportedMediaTypes.Clear();
  43. //默认返回 json
  44. config.Formatters
  45. .JsonFormatter.MediaTypeMappings.Add(
  46. new QueryStringMapping("datatype","json","application/json"));
  47. //返回格式选择
  48. config.Formatters
  49. .XmlFormatter.MediaTypeMappings.Add(
  50. new QueryStringMapping("datatype","xml","application/xml"));
  51. //json 序列化设置
  52. config.Formatters
  53. .JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings()
  54. {
  55. NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
  56. };
  57. return config;
  58. }
  59.  
  60.  
  61. public Task myhandle(IOwinContext context,Func<Task> next)
  62. {
  63. //获取物理文件路径
  64. var path = GetFilePath(context.Request.Path.Value);
  65. //验证路径是否存在
  66. if (File.Exists(path))
  67. {
  68. return SetResponse(context,path);
  69. }
  70.  
  71. //不存在返回下一个请求
  72. return next();
  73. }
  74. public static string GetFilePath(string relPath)
  75. {
  76. return Path.Combine(
  77. AppDomain.CurrentDomain.BaseDirectory,_siteDir,relPath.TrimStart('/').Replace('/','\\'));
  78. }
  79.  
  80. public Task SetResponse(IOwinContext context,string path)
  81. {
  82. var perfix = Path.GetExtension(path);
  83. if(perfix==".html")
  84. context.Response.ContentType = "text/html; charset=utf-8";
  85. else if (perfix == ".js")
  86. context.Response.ContentType = "application/x-javascript";
  87. else if (perfix == ".js")
  88. context.Response.ContentType = "atext/css";
  89. return context.Response.WriteAsync(File.ReadAllText(path));
  90. }
  91.  
  92.  
  93. }
  94. }

app.config
  1. <appSettings>
  2. <add key="Domain" value="localhost"/>
  3. <add key="port" value="9000"/>
  4. <add key="SiteDir" value="..\..\"/>
  5. </appSettings>

web api 的控制器
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading.Tasks;
  5. using System.Web.Http;
  6. using OwinSelfhostSample.models;
  7.  
  8. namespace OwinSelfhostSample.controllers
  9. {
  10. public class ValuesController : ApiController
  11. {
  12. //api/valuses/time
  13. [HttpGet]
  14. [HttpPost]
  15. public timeResult time()
  16. {
  17. return new timeResult()
  18. {
  19. id = DateTime.Now.Ticks,time = DateTime.Now,remark = DateTime.Now.ToString()
  20. };
  21. }
  22. [HttpGet]
  23. [HttpPost]
  24. public dynamic Sleep(int sleep)
  25. {
  26. if (sleep < 1 || sleep>10)
  27. sleep = 1;
  28. sleep *= 1000;
  29.  
  30. var begionTime = DateTime.Now.ToString("HH:mm:ss");
  31. System.Threading.Thread.Sleep(sleep);
  32. var endTime = DateTime.Now.ToString("HH:mm:ss");
  33. return new
  34. {
  35. sleep = sleep,begionTime = begionTime,endTime = endTime
  36. };
  37. }
  38.  
  39. // GET api/values
  40. public IEnumerable<string> Get()
  41. {
  42. return new string[] { "value1","value2" };
  43. }
  44.  
  45. // GET api/values/5
  46. public string Get(int id)
  47. {
  48. return "value";
  49. }
  50.  
  51. // POST api/values
  52. public void Post([FromBody]string value)
  53. {
  54. }
  55.  
  56. // PUT api/values/5
  57. public void Put(int id,[FromBody]string value)
  58. {
  59. }
  60.  
  61. // DELETE api/values/5
  62. public void Delete(int id)
  63. {
  64. }
  65. }
  66. }

猜你在找的设计模式相关文章