Nancy Web Framework

repository·master·Indexed 27 days ago

https://github.com/nancyfx/nancy

A lightweight, low-ceremony web framework for building HTTP-based services on .NET Framework, .NET Core, and Mono. Nancy features a DSL for route declaration, hosting agnosticism (ASP.NET/IIS, WCF, OWIN), built-in content negotiation, and integration with various view engines including Razor and Markdown. It includes a testing framework with a Browser class for request/response cycle verification and uses TinyIOC for dependency injection. Note: Nancy is no longer being maintained.

Tokens
3.2K
Snippets
12
Records
16
Agent score
91%

What's inside Nancy

  1. Important: Nancy is no longer being maintained

    master

    ** Announcement **

    Nancy is no longer being maintained.

    Support and Maintenance: For organizations with production services depending on Nancy, commercial support, maintenance, and migration services may be available through members of the team. Contact nancyfx.help@gmail.com to discuss options.

    Forking: The license is permissive, and forking is encouraged for maintenance purposes. Note that the Nancy name and logos are copyrighted and may not be reused or edited.

  2. Nancy features and capabilities

    master

    Nancy provides several core features for building HTTP services:

    • Hosting Agnostic: Can run on ASP.NET/IIS, WCF, Self-hosting, and any OWIN-compliant server.
    • HTTP Verb Support: Lightweight declarations for GET, HEAD, PUT, POST, DELETE, OPTIONS, and PATCH.
    • View Engine Integration: Supports Razor, Spark, dotLiquid, SuperSimpleViewEngine, and more.
    • Path Matching: Powerful request path matching with advanced parameter capabilities and support for custom implementations.
    • Easy Response Syntax: Directly return types like int, string, HttpStatusCode, or Action<Stream> without explicit casting.
    • Content Negotiation: Built-in support for negotiating content types.
    • Testing Framework: Includes a lightweight framework to verify application behavior.
  3. Create a Nancy module

    master

    Nancy is a lightweight framework for building HTTP services on .NET Framework/Core and Mono. You define your application logic by inheriting from NancyModule and using a Domain Specific Language (DSL) to declare routes for HTTP verbs like GET, POST, PUT, DELETE, etc.

    public class Module : NancyModule
    {
        public Module()
        {
            Get("/greet/{name}", x => {
                return string.Concat("Hello ", x.name);
            });
        }
    }
  4. Configure Dependency Injection in a Bootstrapper

    master

    Nancy uses an internal IOC container called TinyIOC. You can configure dependencies at two different lifecycle stages by overriding methods in your Bootstrapper class:

    1. Application Level: Use ConfigureApplicationContainer to register dependencies that should live for the lifetime of the application (e.g., a database connection store).
    2. Request Level: Use ConfigureRequestContainer to register dependencies that should be scoped to a single HTTP request (e.g., a database session).
    protected override void ConfigureApplicationContainer(TinyIoCContainer container)
    {
        base.ConfigureApplicationContainer(container);
    
        var store = new EmbeddableDocumentStore()
        {
            ConnectionStringName = "RavenDB"
        };
    
        store.Initialize();
    
        container.Register<IDocumentStore>(store);
    }
    
    protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
    {
        base.ConfigureRequestContainer(container, context);
    
        var store = container.Resolve<IDocumentStore>();
        var documentSession = store.OpenSession();
    
        container.Register<IDocumentSession>(documentSession);
    }
  5. Hook into the request pipeline

    master

    You can modify the request or response by adding items to the pipeline. For example, you can use RequestStartup to add a delegate to the AfterRequest pipeline to perform actions like saving database changes or disposing of resources after a request completes.

    protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
    {
        base.RequestStartup(container, pipelines, context);
    
        pipelines.AfterRequest.AddItemToEndOfPipeline(
            (ctx) =>
            {
                var documentSession = container.Resolve<IDocumentSession>();
    
                if (ctx.Response.StatusCode != HttpStatusCode.InternalServerError)
                {
                    documentSession.SaveChanges();
                }
    
                documentSession.Dispose();
            });
    }
  6. Run Nancy sample applications

    master

    Working samples are provided in the /sample directory of the repository. To run them, use the provided build scripts depending on your operating system:

    • Windows (PowerShell): ./build.ps1
    • Linux/macOS (Bash): ./build.sh
  7. Use Content Negotiation to return different formats

    master

    Nancy has built-in content negotiation. You can use the Negotiate object within a route to return different models or views based on the client's Accept header, or to provide custom headers.

    Get["/"] = parameters => {
        return Negotiate
            .WithModel(new RatPack {FirstName = "Nancy "})
            .WithMediaRangeModel("text/html", new RatPack {FirstName = "Nancy fancy pants"})
            .WithView("negotiatedview")
            .WithHeader("X-Custom", "SomeValue");
    };
  8. Test the request/response cycle with the Browser class

    master

    Nancy provides a testing library that allows you to test the full request/response cycle without needing to hit a real server. This is useful for verifying status codes, headers, and content negotiation. You can use the Browser class to simulate requests.

    [Fact]
    public void GetData_WhenRequested_ShouldReturnOKStatusCode()
    {
        var browser = new Browser();
        var response = await browser.Get("/GetData", (with) =>
        {
            with.Header("Authorization", "Bearer johnsmith");
            with.Header("Accept", "application/json");
            with.HttpRequest();
        });
    
        Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
    }
  9. Configure Nancy for ASP.NET hosting via web.config

    master

    To host a Nancy application within an ASP.NET environment, you must register the NancyHttpRequestHandler in your web.config. This allows Nancy to intercept incoming requests.

    Depending on your IIS mode (Classic vs. Integrated), you may need to add the handler to both <system.web>/<httpHandlers> and <system.webServer>/<handlers>.

    <configuration>
      <system.web>
        <httpHandlers>
          <add verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*"/>
        </httpHandlers>
      </system.web>
    
      <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
        <httpErrors existingResponse="PassThrough"/>
        <handlers>
          <add name="Nancy" verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*"/>
        </handlers>
      </system.webServer>
    </configuration>
  10. Configure Nancy Razor View Engine build providers

    master

    To use the Nancy Razor View Engine in an ASP.NET environment, you must register the build providers in the <system.web>/<compilation>/<buildProviders> section of your web.config. This enables the application to handle .cshtml and .vbhtml files using Nancy's specific build providers.

    <system.web>
      <compilation>
        <buildProviders>
          <add extension=".cshtml" type="Nancy.ViewEngines.Razor.BuildProviders.NancyCSharpRazorBuildProvider, Nancy.ViewEngines.Razor.BuildProviders" />
          <add extension=".vbhtml" type="Nancy.ViewEngines.Razor.BuildProviders.NancyVisualBasicRazorBuildProvider, Nancy.ViewEngines.Razor.BuildProviders" />
        </buildProviders>
      </compilation>
    </system.web>