OwinSelfHost自宿主的使用
2018-11-20 本文已影响1人
HapplyFox
Owin介绍看上篇 链接
OWIN将多种应用框架使用统一的接口来实现各框架之间的适配!
新建控制台项目


新建普通控制台项目,框架类型最好选择.NET Framework4.6,为了下一篇的内容做铺垫。
添加Nuget包
安装OWIN自宿主的包包
1、通过程序包管理器控制台
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
2、通过Nuget包可视化工具

新建Startup类
/// <summary>
/// OWIN应用程序入口
/// </summary>
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
//配置路由
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//将默认xml返回数据格式改为json
config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
config.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("datatype", "json", "application/json"));
app.UseWebApi(config);
// 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888
}
}
添加几个测试用的Controller
其实就是webapi或者webmvc里的controller,这里以webapi为例说明
public class HomeController : ApiController
{
public object Get()
{
return new { code = 1, msg = "OK HomeController" };
}
}
public class VideoController : ApiController
{
public object Get()
{
return new { code = 2, msg = "OK VideoController" };
}
}
主程序入口启动Owin
string baseAddress = "http://192.168.2.71:9000/";
Microsoft.Owin.Hosting.WebApp.Start<Startup>(url: baseAddress);
Console.WriteLine("程序已启动,按任意键退出");
Console.ReadLine();
查看结果

浏览器,访问一下URL即可看到时结果了
