监听线程
#p#分页标题#e#class Program
{
static void Main(string[] args)
{
//监听地址
string baseAddress = string.Format("http://{0}:{1}/",
System.Configuration.ConfigurationManager.AppSettings.Get("Domain"),
#p#分页标题#e# 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();
} #p#分页标题#e#
}
}
Startup 请求处理程序(WebApp.Start<T>() 方法会自动执行 T.Configuration() 方法)
[csharp] view plain copy
using System.IO;
#p#分页标题#e#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;
#p#分页标题#e#
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
#p#分页标题#e# // parameter in the WebApp.Start method.
public void Configuration(IAppBuilder app)
{
// web api 接口
HttpConfiguration config = InitWebApiConfig();
app.UseWebApi(config);
//静态文件托管
app.Use((context, fun) => #p#分页标题#e#
{
return myhandle(context, fun);
});
}
/// <summary>
/// 路由初始化
/// </summary>
public HttpConfiguration InitWebApiConfig()
#p#分页标题#e# {
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "api/{controller}/{action}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters
#p#分页标题#e# .XmlFormatter.SupportedMediaTypes.Clear();
//默认返回 json
config.Formatters
.JsonFormatter.MediaTypeMappings.Add(
new QueryStringMapping("datatype", "json", "application/json"));
//返回格式选择
config.Formatters
.XmlFormatter.MediaTypeMappings.Add( #p#分页标题#e#
new QueryStringMapping("datatype", "xml", "application/xml"));
//json 序列化设置
config.Formatters
.JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings()
{
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
};
#p#分页标题#e# return config;
}
public Task myhandle(IOwinContext context, Func<Task> next)
{
//获取物理文件路径
var path = GetFilePath(context.Request.Path.Value);
//验证路径是否存在#p#分页标题#e#
if (File.Exists(path))
{
return SetResponse(context,path);
}
//不存在返回下一个请求
return next();
}
#p#分页标题#e#public static string GetFilePath(string relPath)
{
return Path.Combine(
AppDomain.CurrentDomain.BaseDirectory
, _siteDir
, relPath.TrimStart('/').Replace('/','\\'));
}
#p#分页标题#e#
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")
#p#分页标题#e# context.Response.ContentType = "application/x-javascript";
else if (perfix == ".js")
context.Response.ContentType = "atext/css";
return context.Response.WriteAsync(File.ReadAllText(path));
}
}
#p#分页标题#e#}
app.config
[csharp] view plain copy
<appSettings>
<add key="Domain" value="localhost"/>
<add key="port" value="9000"#p#分页标题#e#/>
<add key="SiteDir" value="..\..\"/>
</appSettings>
[csharp] view plain copy
<runtime>
<!--更改程序集清单绑定-->
#p#分页标题#e# <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 的控制器
#p#分页标题#e#
[csharp] view plain copy
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using#p#分页标题#e# System.Web.Http;
using OwinSelfhostSample.models;
namespace OwinSelfhostSample.controllers
{
public class ValuesController : ApiController
{
//api/valuses/time
[HttpGet]
[HttpPost] #p#分页标题#e#
public timeResult time()
{
return new timeResult()
{
id = DateTime.Now.Ticks,
time = DateTime.Now,
remark = DateTime.Now.ToString()
};
}
#p#分页标题#e# [HttpGet]
[HttpPost]
public dynamic Sleep(int sleep)
{
if (sleep < 1 || sleep>10)
sleep = 1;
sleep *= 1000;
var begionTime = DateTime.Now.ToString("HH:mm:ss");
#p#分页标题#e# System.Threading.Thread.Sleep(sleep);
var endTime = DateTime.Now.ToString("HH:mm:ss");
return new
{
sleep = sleep,
begionTime = begionTime,
endTime = endTime
};
}
#p#分页标题#e#
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
#p#分页标题#e#// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void#p#分页标题#e# Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
#p#分页标题#e#
// DELETE api/values/5
public void Delete(int id)
{
}
}
}