Skip to main content

Botwin offers an interesting alternative option for routing with ASP.NET Core

NancyFx is a great alternative to ASP.NET if you want to make elegant little web apis like this:

public class SampleModule : Nancy.NancyModule

{
public SampleModule()
{
Get["/"] = _ => "Hello World!";
}
}

However, it may be that you want a routing style - the way you define your routes - that is like NancyFx BUT you want to use ASP.NET. Botwin is a library that lets you do just that. They say:

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.

You can plug Botwin into your existing ASP.NET Core application, or you can even add a basic started Botwin app to "dotnet new" like this:

C:\botwinexample> dotnet new -i BotwinTemplate

C:\botwinexample> dotnet new botwin -n MyBotwinApp
C:\botwinexample> dir
10/11/2017 10:14 PM 284 HomeModule.cs
10/11/2017 10:14 PM 470 MyBotwinApp.csproj
10/11/2017 10:14 PM 421 Program.cs
10/11/2017 10:14 PM 408 Startup.cs
4 File(s) 1,583 bytes

You add Botwin as a service to your ASP.NET Core app:

public class Startup

{ public void ConfigureServices(IServiceCollection services) { services.AddBotwin(); } public void Configure(IApplicationBuilder app) { app.UseBotwin(); }
}

And then add 'Modules' like this:

namespace MyBotwinApp
{
    using Botwin;
    using Microsoft.AspNetCore.Http;
    public class HomeModule : BotwinModule
    {
        public HomeModule()
        {
            Get("/", async(req, res, routeData) => await res.WriteAsync("Hello from Botwin!"));
        }
    }
}

That's a hello world. Let's try something more interesting. You can have Before and After hooks like this:

public class HooksModule : BotwinModule

{
public HooksModule()
{
this.Before = async (ctx) =>
{
ctx.Response.StatusCode = 402;
await ctx.Response.WriteAsync("Pay up you filthy animal");
return false;
};

this.Get("/hooks", async (req, res, routeData) => await res.WriteAsync("Can't catch me here"));

this.After = async (ctx) => await ctx.Response.WriteAsync("Don't forget you owe me big bucks!");
}
}

Here's a more complex example. See how they do a BindAndValidate in the Post() where they check for a valid Actor before working with it.

public class ActorsModule : BotwinModule

{
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);
});
}

What do you think about the choices you have with ASP.NET Core? Some people feel like the amount of plugability is overwhelming, but I find the flexibility heartening. Go check out Botwin and, hopefully, help out and contribute to open source!


Sponsor: Get the latest JetBrains Rider preview for .NET Core 2.0 support, Value Tracking and Call Tracking, MSTest runner, new code inspections and refactorings, and the Parallel Stacks view in debugger.



© 2017 Scott Hanselman. All rights reserved.
     


from Scott Hanselman's Blog http://feeds.hanselman.com/~/468631182/0/scotthanselman~Botwin-offers-an-interesting-alternative-option-for-routing-with-ASPNET-Core.aspx

Comments

Popular posts from this blog

dotnet sdk list and dotnet sdk latest

Can someone make .NET Core better with a simple global command? Fanie Reynders did and he did it in a simple and elegant way. I'm envious, in fact, because I spec'ed this exact thing out in a meeting a few months ago but I could have just done it like he did and I would have used fewer keystrokes! Last year when .NET Core was just getting started, there was a "DNVM" helper command that you could use to simplify dealing with multiple versions of the .NET SDK on one machine. Later, rather than 'switching global SDK versions,' switching was simplified to be handled on a folder by folder basis. That meant that if you had a project in a folder with no global.json that pinned the SDK version, your project would use the latest installed version. If you liked, you could create a global.json file and pin your project's folder to a specific version. Great, but I would constantly have to google to remember the format for the global.json file, and I'd constan...

15 Web Design Trends to Watch in 2018

The modern world is full of extraordinary things that influence our imagination and mood. Our soul needs a perfect atmosphere and impressive spots. To apply such things in practice, we have submitted the list of the web trends that deserve your attention. Robert frost design analysis will meet all your wishes and expectations. Image Source Web Design Trends to Watch in 2018 1. More Organic Shapes Until this year, web design, as well as mobile design, were based on the right-angled and sharp-edged shapes. However, it seems that this year will bring some significant changes in the field of web design. The recent trends will offer the absolute rounded corners. In addition, the web design of 2018 will make the real things look like the cartoonish ones. 2.   Bold Minimalism Although some of you may think that this web design trend will not attract the Internet users. Indeed, the notion of minimalism is often associated with boredom and dullness. However, in this case, bold ...

R vs Python for Machine Learning

There are so many things to learn before to choose which language is good for Machine Learning. We will discuss each and everything about R as well as Python and the situation or problem in which situation we have to use which language. Let’s start Python and R are the two most Commonly used Programming Languages for Machine Learning and because of the popularity of both the languages Novice or you can say fresher are getting confused, whether they should choose R or Python language to commence their career in the Machine learning domain. Don’t worry guys through this article we will discuss R vs Python for Machine Learning. So, without exaggerating this article let’s get started. We will start it from the very Basics things or definitions. R vs Python for Machine Learning Introduction R is a programming language made by statisticians and data miners for statistical analysis and graphics supported by R foundation for statistical computing. R also provides high-quality graphics and...