iis ajax访问html文件,使用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服务器,下面只复制了一些关键部分的 代码。

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

控制台程序

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)

{

}

}

}

总结

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值