您的位置:首页 > Web前端 > HTML

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

2016-07-22 11:41 711 查看
最近试用了一下 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

控制台程序

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<Startup>(url: baseAddress))
{
Console.WriteLine("host 已启动:{0}", DateTime.Now);
Console.WriteLine("访问:{0}/page/index.html", baseAddress);
Console.ReadLine();
}
}

}


Startup 请求处理程序(WebApp.Start<T>() 方法会自动执行 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);
});
}
/// <summary>
/// 路由初始化
/// </summary>
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<Task> 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

<appSettings>
<add key="Domain" value="localhost"/>
<add key="port" value="9000"/>
<add key="SiteDir" value="..\..\"/>
</appSettings>
  <runtime>
    <!--更改程序集清单绑定-->
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>


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<string> 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)
{
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: