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.
About Scott
Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.
About Newsletter
routeData.As<int>("id")seems a little clunky, only in that the route attribute name and type were already stated in the line just above. The ideal would be a strongly-typed "routeData.id" but I'd be hard pressed to figure out the best way to accomplish that without having to declare a POCO class manually or involving T4 templates.
Are there any examples showing how to post a JSON object with a few fields and an array or two, receive it on the server, call a business method to get a different C# POCO object and return that to the caller?
Is there an example of how to create a default handler for a controller equivalent to handle all routes that are invalid or valid with incorrect input types? ASP.NET MVC is missing that and could output it in the debug output window.
res.AsJson(myObject)or
res.Negotiate(myObject)
As Botwin uses the ASP.NET Core routing you can just specify a route with "/*" as a catch-all route. If your route has an invalid type in a POST/PUT for example the validation will fail and you can check this and return, also shown in the above example. See
BindAndValidate
My big issue is that .NET is now my work ecosystem and my play ecosystem so my work/life balance is completely shot.
Comments are closed.