rrbrbNancyFx是一个轻量级的web开发框架(基于.net),我使用它,主要是它可以不依赖IIS(因为我当前的项目都是轻量级的BS框架),可以selfhost。
Nancy的网址为:http://nancyfx.org/
为了在VS中快速开发,可以下载它的项目模板,下载地址:http://sidewaffle.com/
我使用的是VS2015,下载安装后,就可以创建Nancy的selfhost项目了,如下图:
创建完项目后
可看的地方有四个
1、Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
using
System;
using
Nancy.Hosting.Self;
namespace
TestSelfHostWeb
{
class
Program
{
static
void
Main(
string
[] args)
{
var
uri =
new
Uri(
"http://localhost:3579"
);
using
(
var
host =
new
NancyHost(uri))
{
host.Start();
Console.WriteLine(
"Your application is running on "
+ uri);
Console.WriteLine(
"Press any [Enter] to close the host."
);
Console.ReadLine();
}
}
}
}
|
很明显,是selfhost的主要代码,很简单,就是开启了一个本机的3579端口,用来接收Browser的请求,注意的是启动时要以管理员身份启动。
2、IndexModule.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
using
Nancy;
namespace
TestSelfHostWeb.Modules
{
public
class
IndexModule : NancyModule
{
public
IndexModule()
{
Get[
"/"
] = parameters =>
{
return
View[
"index"
];
};
}
}
}
|
也是Nancy比较爽的地方,只要继承NancyModule就可以自动挂载在host中,Browser输入正确的Url就可以访问了。当前Get对应的是get请求,自然有post等其他请求了。
3、index.cshtml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
meta
charset
=
"utf-8"
/>
<
title
>TestSelfHostWeb</
title
>
<
style
type
=
"text/css"
>
body {
text-align: center;
}
</
style
>
</
head
>
<
body
>
<
img
src
=
"~/Content/nancy-logo.png"
alt
=
"Nancy logo"
/><
br
/>
This view was rendered using the Nancy Razor view engine
</
body
>
</
html
>
|
这是个标准Razor页面,与asp.netmvc中的Razor是一样的,不多说了。
4、Bootstrapper.cs
1
2
3
4
5
6
7
8
9
10
|
using
Nancy;
namespace
TestSelfHostWeb
{
public
class
Bootstrapper : DefaultNancyBootstrapper
{
// The bootstrapper enables you to reconfigure the composition of the framework,
// by overriding the various methods and properties.
// For more information https://github.com/NancyFx/Nancy/wiki/Bootstrapper
}
}
|
是web的启动入口,有点像asp.net中的Global文件,可以重写一些类成员。
接下来可以跑一下了,可以以管理员身份运行VS,直接F5启动程序(报错也继续),也可以找到执行程序,以管理员运行,然后在Browser中输入本地ID和端口,效果如下:
本文转自桂素伟51CTO博客,原文链接: http://blog.51cto.com/axzxs/1773988,如需转载请自行联系原作者