LoginSignup
6
6

More than 5 years have passed since last update.

Nancy入門してみた。

Last updated at Posted at 2013-06-30

なぜ、Nancy?

OmniSharpServerというものがありまして、この仕組みを調べていたらNancyにたどり着きました。

「なぜ、OmniSharpServer?」っていう理由はココに書いてあることが始まりです。

まぁこんな感じでNancyを入門してみました。

Hello World

Nancyを導入するにあたって必要となるのがNuGet.exeです。下記のURLからダウンロードできます。

Nancyを使うにはNuGetから必要なアセンブリをダウンロードしてくるしかないっぽいです。

まぁそんなわけで、以下のコマンドでアセンブリをダウンロード出来ます。

$ ./NuGet.exe install Nancy
Successfully installed 'Nancy 0.17.1'.
$./NuGet.exe install Nancy.Hosting.Self
Attempting to resolve dependency 'Nancy (? 0.17.1)'.
Successfully installed 'Nancy.Hosting.Aspnet 0.17.1'.
$ ls
Nancy.0.17.1/  NuGet.exe* Nancy.Hosting.Self.0.17.1/
$ ls Nancy.0.17.1/lib/net40
Nancy.dll*
$ ls Nancy.Hosting.Self.0.17.1/lib/net40
Nancy.Hosting.Self.dll*

で次に、実際にNancyを使うコードが下記のような感じになります。

// sample.cs

using System;
using Nancy.Hosting.Self;

public class Sample
{
    public static void Main()
    {
        var nancyHost = new Nancy.Hosting.Self.NancyHost(new Uri("http://localhost:2000"));

        // ホストサーバー起動
        nancyHost.Start();

        // ホストサーバーがすぐに終了しないようにとりあえず入力を求めて止めておく。
        Console.ReadLine();

        // ホストサーバー停止
        nancyHost.Stop();
    }
}

// Nancy.NancyModule を継承するだけでOK
public class SampleModule : Nancy.NancyModule
{
    public SampleModule()
    {
        // 'http://localhost:2000/'でアクセスされた時に処理
        Get["/"] = _ => "Hello World!";
    }
}

ビルドは以下のような感じで出来ます。

色々とめんどうなのでアセンブリをカレントディレクトリにコピーしてきています。

$ cp Nancy.0.17.1/lib/net40/Nancy.dll  .
$ cp Nancy.Hosting.Self.0.17.1/lib/net40/Nancy.dll  .
$ ls
Nancy.0.17.1/
Nancy.Hosting.Self.0.17.1/
Nancy.Hosting.Self.dll*
Nancy.dll*
NuGet.exe*
sample.cs
$ csc /R:Nancy.dll /R:Nancy.Hosting.Self.dll ./sample.cs
Microsoft (R) Visual C# Compiler Version 4.0.30319.17929
for Microsoft (R) .NET Framework 4.5
Copyright (C) Microsoft Corporation. All rights reserved.

で、最後にこのURLを有効にするためにACLさんに許可してもらいます。(DOMAIN\usernameの部分は各自の環境に合わせて)

netsh http add urlacl url=http://+:2000/ user=DOMAIN\username

実際に実行してアクセスしてみるとこんな感じになります。

nancy-hello.png

関連サイト

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6