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

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

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

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

该组件依赖 iis。

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

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

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

控制台程序

class Program

{

static void Main(string[] args)

{

//监听地址

string baseAddress = string.Format("http://{0}:{1}/",System.Configuration.ConfigurationManager.AppSettings.Get("Domain"),System.Configuration.ConfigurationManager.AppSettings.Get("Port"));

//启动监听

using (WebApp.Start(url: baseAddress))

{

Console.WriteLine("host 已启动:{0}",DateTime.Now);

Console.WriteLine("访问:{0}/page/index.html",baseAddress);

Console.ReadLine();

}

}

}

Startup 请求处理程序(WebApp.Start() 方法会自动执行 T.Configuration() 方法)

using System.IO;

using System.Net.Http.Formatting;

using Owin;

using Microsoft.Owin;

using System;

using System.Collections.Generic;

using System.Text;

using System.Threading.Tasks;

using System.Web.Http;

namespace OwinSelfhostSample

{

class Startup

{

private static string _siteDir = System.Configuration.ConfigurationManager.AppSettings.Get("SiteDir");

// This code configures Web API. The Startup class is specified as a type

// parameter in the WebApp.Start method.

public void Configuration(IAppBuilder app)

{

// web api 接口

HttpConfiguration config = InitWebApiConfig();

app.UseWebApi(config);

//静态文件托管

app.Use((context,fun) =>

{

return myhandle(context,fun);

});

}

///

/// 路由初始化

///

public HttpConfiguration InitWebApiConfig()

{

HttpConfiguration config = new HttpConfiguration();

config.Routes.MapHttpRoute(

name: "Default",routeTemplate: "api/{controller}/{action}",defaults: new { id = RouteParameter.Optional }

);

config.Formatters

.XmlFormatter.SupportedMediaTypes.Clear();

//默认返回 json

config.Formatters

.JsonFormatter.MediaTypeMappings.Add(

new QueryStringMapping("datatype","json","application/json"));

//返回格式选择

config.Formatters

.XmlFormatter.MediaTypeMappings.Add(

new QueryStringMapping("datatype","xml","application/xml"));

//json 序列化设置

config.Formatters

.JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings()

{

NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore

};

return config;

}

public Task myhandle(IOwinContext context,Func next)

{

//获取物理文件路径

var path = GetFilePath(context.Request.Path.Value);

//验证路径是否存在

if (File.Exists(path))

{

return SetResponse(context,path);

}

//不存在返回下一个请求

return next();

}

public static string GetFilePath(string relPath)

{

return Path.Combine(

AppDomain.CurrentDomain.BaseDirectory,_siteDir,relPath.TrimStart('/').Replace('/','\\'));

}

public Task SetResponse(IOwinContext context,string path)

{

var perfix = Path.GetExtension(path);

if(perfix==".html")

context.Response.ContentType = "text/html; charset=utf-8";

else if (perfix == ".js")

context.Response.ContentType = "application/x-javascript";

else if (perfix == ".js")

context.Response.ContentType = "atext/css";

return context.Response.WriteAsync(File.ReadAllText(path));

}

}

}

app.config

web api 的控制器

using System;

using System.Collections.Generic;

using System.Text;

using System.Threading.Tasks;

using System.Web.Http;

using OwinSelfhostSample.models;

namespace OwinSelfhostSample.controllers

{

public class ValuesController : ApiController

{

//api/valuses/time

[HttpGet]

[HttpPost]

public timeResult time()

{

return new timeResult()

{

id = DateTime.Now.Ticks,time = DateTime.Now,remark = DateTime.Now.ToString()

};

}

[HttpGet]

[HttpPost]

public dynamic Sleep(int sleep)

{

if (sleep < 1 || sleep>10)

sleep = 1;

sleep *= 1000;

var begionTime = DateTime.Now.ToString("HH:mm:ss");

System.Threading.Thread.Sleep(sleep);

var endTime = DateTime.Now.ToString("HH:mm:ss");

return new

{

sleep = sleep,begionTime = begionTime,endTime = endTime

};

}

// GET api/values

public IEnumerable Get()

{

return new string[] { "value1","value2" };

}

// GET api/values/5

public string Get(int id)

{

return "value";

}

// POST api/values

public void Post([FromBody]string value)

{

}

// PUT api/values/5

public void Put(int id,[FromBody]string value)

{

}

// DELETE api/values/5

public void Delete(int id)

{

}

}

}

总结

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐