Nancy之开篇

rrbrbNancyFx是一个轻量级的web开发框架(基于.net),我使用它,主要是它可以不依赖IIS(因为我当前的项目都是轻量级的BS框架),可以selfhost

Nancy的网址为:http://nancyfx.org/

为了在VS中快速开发,可以下载它的项目模板,下载地址:http://sidewaffle.com/

我使用的是VS2015,下载安装后,就可以创建Nancyselfhost项目了,如下图:

wKiom1c5kMKDziiOAADwZ5_1m78593.png


创建完项目后

wKioL1c5kaqQOiLvAABbuaH3oj4061.png

可看的地方有四个

1、Program.cs

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

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

<!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

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和端口,效果如下:

wKioL1c5lTSTP2Z0AABlMyKtTr8773.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值