Nancy跨平台开发总结(二)Hello World

按照惯例,还是先建一个简单的Hello Word项目作为课程的开发

  • 用visual studio新建一个最基本的ASP.NET Web Application项目, 名称为WebSite。Mono目前兼容的.net 版本是4.5,所以这里使用.net framework 4.5
  • 用Nuget安装如下的开发包
    • Nancy
    • Nancy.Viewengines.Razor:使用Razor视图引擎
    • Microsoft.Owin.Host.SystemWeb:使用Katana作为Owin的Web宿主
    • Nancy.Owin
  • 模仿标准的Asp.net MVC项目建立目录,使它看起来更像一个.net mvc project.添加两个MVC View Page(Razor)文件,页面文件的代码也与Asp.net MVC项目里的类似。
    • _ViewStart.cshtml代码
      @{
              Layout = "Shared/_Layout.cshtml";
      }
    • _Layout.cshtml代码

      <!DOCTYPE html>

      <html>

      <head>

          <title>@ViewBag.Title</title>

          <meta charset="utf-8" />

          <meta name="viewport" content="width=device-width, initial-scale=1.0">

      </head>

      <body>

          <div class="container body-content">

              @RenderBody()

          </div>

      </body>

      </html>

       

  • 在根目录下新建一个OWIN Startup class,代码如下
    public class Startup
    {
            public void Configuration(IAppBuilder app)
            {
                app.UseNancy();
            }
    }
  • Models中添加类HomeViewModel
    public class HomeViewModel
    {
            public string Name { get; set; }
    }
  • Controller中添加类IndexController,继承自NancyModule,这个类就是控制器.与asp.net WebAPI不同的,Nancy在构造函数中定义Get,Post,Put,Delete路由路径及方法.
    using Nancy;
    using Nancy.Security;
    using WebSite.Models;
    public class IndexController:NancyModule
    {
           public IndexController()
           {
                Get["/"] = _ => Index();
                Get["/Index"] = _ => Index();
           }
    
           private dynamic Index()
           {
                this.ViewBag.Title = "Hello Word";
                var model = new HomeViewModel()
                {
                    Name = "Helle Word,Carl!"
                };
                return View["Home/Index", model];
           }
    }
  • 在Home下添加Index.cshtml视图文件,在页面显示model的Name属性值
    <div>
        @Model.Name
    </div>
  • 配置WebConfig,配置katana web宿主的支持
    <!—katana-Asp.net Owin Host支持-->
    <appSettings>
        <add key="owin:HandleAllRequests" value="true"/>
    </appSettings>
    

      

 

posted @ 2016-01-28 13:32  凌锋  阅读(822)  评论(0编辑  收藏  举报