Giter Club home page Giter Club logo

carter's Introduction

Carter

NuGet Version

Carter is a library that allows Nancy-esque routing for use with ASP.Net Core.

This is not a framework, it simply builds on top of Microsoft.AspNetCore.Routing allowing you to have more elegant routing rather than have attribute routing, convention routing, ASP.Net Controllers or IRouteBuilder extensions.

For a better understanding, take a good look at the samples inside this repo. The sample demonstrates usages of elegant extensions around common ASP.Net Core types as shown below.

Other extensions include:

  • Bind/BindAndValidate<T> - FluentValidation extensions to validate incoming HTTP requests.

  • BindFile/BindFiles/BindFileAndSave/BindFilesAndSave - Allows you easily get access to a file/files that has been uploaded or alternatively you can call BindFilesAndSave and this will save it to a path you specify

  • Global Before/After hooks for every request.

  • Before/After hooks to the routes defined in a Carter module.

  • Routes to use in common ASP.Net Core middleware eg. app.UseExceptionHandler("/errorhandler");.

  • IStatusCodeHandlers are also an option as the ASP.Net Core UseStatusCodePages middleware is not elegant enough IMO. IStatusCodeHandlers allow you to define what happens when one of your routes returns a specific status code. An example usage is shown in the sample.

  • IResponseNegotiators allow you to define how the response should look on a certain Accept header. Handling JSON is built in and the default response but implementing an interface allows the user to choose how they want to represent resources.

  • All interface implementations are registered into ASP.Net Core DI automatically, implement the interface and off you go.

  • Supports two different routing APIs.

    (i)

    this.Get("/actors/{id:int}", async (req, res, routeData) =>
    {
        var person = actorProvider.Get(routeData.As<int>("id"));
        await res.Negotiate(person);
    });

    (ii)

    this.Get("/actors/{id:int}", async (ctx) =>
    {
        var person = actorProvider.Get(ctx.GetRouteData().As<int>("id"));
        await ctx.Response.Negotiate(person);
    });

Where does the name "Carter" come from?

I have been a huge fan of, and core contributor to Nancy, the best .Net web framework, for many years, and the name "Nancy" came about due to it being inspired from Sinatra the Ruby web framework. Frank Sinatra had a daughter called Nancy and so that's where it came from.

I was also trying to think of a derivative name, and I had recently listened to the song Empire State of Mind where Jay-Z declares he is the new Sinatra. His real name is Shaun Carter so I took Carter and here we are!

Getting Started

You can get started using either the template or by adding the package manually to a new or existing application

Template

https://www.nuget.org/packages/CarterTemplate/

  1. Install the template - dotnet new -i CarterTemplate

  2. Create a new application using template - dotnet new Carter -n MyCarterApp

  3. Run the application - dotnet run

Package

https://www.nuget.org/packages/Carter

  1. Create a new empty ASP.NET Core application - dotnet new web -n MyCarterApp

  2. Change into the new project location - cd ./MyCarterApp

  3. Add Carter package - dotnet add package carter

  4. Modify your Startup.cs to use Carter

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCarter();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseCarter();
    }
}
  1. Create a new Module
    public class HomeModule : CarterModule
    {
        public HomeModule()
        {
            Get("/", async (req, res, routeData) => await res.WriteAsync("Hello from Carter!"));
        }
    }
  1. Run the application - dotnet run

Sample

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IActorProvider, ActorProvider>();
        services.AddCarter();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseCarter();
    }
}

public class ActorsModule : CarterModule
{
    public ActorsModule(IActorProvider actorProvider)
    {
        this.Get("/actors", async (req, res, routeData) =>
        {
            var people = actorProvider.Get();
            await res.AsJson(people);
        });

        this.Get("/actors/{id:int}", async (req, res, routeData) =>
        {
            var person = actorProvider.Get(routeData.As<int>("id"));
            await res.Negotiate(person);
        });

        this.Put("/actors/{id:int}", async (req, res, routeData) =>
        {
            var result = req.BindAndValidate<Actor>();

            if (!result.ValidationResult.IsValid)
            {
                res.StatusCode = 422;
                await res.Negotiate(result.ValidationResult.GetFormattedErrors());
                return;
            }

            // Update the user in your database

            res.StatusCode = 204;
        });

        this.Post("/actors", async (req, res, routeData) =>
        {
            var result = req.BindAndValidate<Actor>();

            if (!result.ValidationResult.IsValid)
            {
                res.StatusCode = 422;
                await res.Negotiate(result.ValidationResult.GetFormattedErrors());
                return;
            }

            // Save the user in your database

            res.StatusCode = 201;
            await res.Negotiate(result.Data);
        });

    }
}

More samples

carter's People

Contributors

jchannon avatar joestead avatar poke avatar j0nnyhughes avatar pdwetz avatar sphiecoh avatar bugagain avatar josephwoodward avatar jussimattila avatar fdipuma avatar gep13 avatar henkmollema avatar jasonmitchell avatar jeremyabbott avatar grandchamp avatar pauliusnorkus avatar petedishman avatar ragingkore avatar azure-pipelines[bot] avatar jonathanschein avatar slang25 avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.