码迷,mamicode.com
首页 > 其他好文 > 详细

Nancy之开篇

时间:2016-05-16 20:09:31      阅读:778      评论:0      收藏:0      [点我收藏+]

标签:nancy   selfhost   

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

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

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

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

技术分享


创建完项目后

技术分享

可看的地方有四个

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

技术分享

本文出自 “桂素伟” 博客,请务必保留此出处http://axzxs.blog.51cto.com/730810/1773988

Nancy之开篇

标签:nancy   selfhost   

原文地址:http://axzxs.blog.51cto.com/730810/1773988

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!