Nancy框架的Owin使用
先建一个空的Web项目
然后往Nuget库里面添加Nancy包
- Nancy
- Nancy.Owin
- Nancy.ViewEnglines.Spark
然后添加Models,Module,Views三个文件夹
往Models文件夹里面添加Index类
public string StatusMessage { get; set; }
然后往Module文件夹里面添加MainModule类
public MainModule()
{
Get("",Lexan=>Root(Lexan));
}
private object Root(dynamic o)
{
var env = GetOwinEnvironmentValue<IDictionary<string, object>>(this.Context.Items, NancyMiddleware.RequestEnvironmentKey);
if (env==null)
{
return "未在 owin 主机上运行";
}
var requestMethod = GetOwinEnvironmentValue<string>(env,"owin的请求方法");
var requestPath = GetOwinEnvironmentValue<string>(env,"owin的请求路径");
var owinVersion = GetOwinEnvironmentValue<string>(env,"owin的版本");
var statusMessage = string.Format("向 {1} 发出了一个 {0} 请求, 它在 owin 上运行{2}",requestMethod,requestPath,owinVersion);
return View["Root",new Models.Index { StatusMessage=statusMessage}];
}
private static T GetOwinEnvironmentValue<T>(IDictionary<string,object> env,string name,T defaultValue=default(T))
{
object value;
return env.TryGetValue(name,out value)&& value is T ?(T)value:defaultValue;
}
然后在根目录添加一个Startup类
public void Configuration(IAppBuilder app)
{
app.UseNancy();
}
然后在Views文件夹中添加Root.html
<viewdata model="HostingOwinDemo.Models.Index" />
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Nancy Owin Host</title>
</head>
<body>
<h1>Nancy Owin Host</h1>
<p>这是通过 OWIN 宿主渲染的视图 ${Model.StatusMessage}</p>
</body>
</html>
然后修改Web.config配置文件
<appSettings>
<add key="owin:HandleAllRequests" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2"/>
<!--<httpRuntime targetFramework="4.5.2"/>-->
<httpRuntime maxRequestLength=""/>
<pages controlRenderingCompatibilityVersion="4.0"/>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength=""/>
</requestFiltering>
</security>
</system.webServer>
然后按F5进行调试运行,有点乱码
谢谢欣赏