Thursday, December 1, 2022
HomeSoftware DevelopmentCarter Group for ASP.NET Core means satisfying Net APIs on the innovative

Carter Group for ASP.NET Core means satisfying Net APIs on the innovative

[ad_1]


I blogged concerning the open supply Carter Group Mission in 2019. Let’s verify in and see what is going on on at present in 2021!

With .NET 6 on the close to horizon, one notes that Carter has a net6 department. Per their web site, that is the purpose of the Carter framework:

Carter is framework that could be a skinny layer of extension strategies and performance over ASP.NET Core permitting code to be extra express and most significantly extra satisfying.

As of at present you may deliver Carter into your .NET 6 tasks like this:

dotnet add bundle Carter --version 6.0.0-pre2

And the .NET 6 samples are underneath lively improvement! Let’s deliver it down with a clone, change to the net6 department and provides it a go.

Here is as easy Net API pattern with Carter that returns an inventory of actors at localhost:5001/actors

utilizing Carter;
utilizing CarterSample.Options.Actors;
utilizing Microsoft.AspNetCore.Builder;
utilizing Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);
builder.Companies.AddSingleton<IActorProvider, ActorProvider>();
builder.Companies.AddCarter();

var app = builder.Construct();

app.MapCarter();
app.Run();

Good! That is utilizing new .NET 6 options so there is no Primary(), it is implied. The builder has an ActorProvider added as a Singleton. I guess we’ll use that after we ask for /actors in our browser or favourite HTTP API consumer.

public class ActorsModule : ICarterModule
{
public void AddRoutes(IEndpointRouteBuilder app)
{
app.MapGet("/actors", (IActorProvider actorProvider, HttpResponse res) =>
{
var individuals = actorProvider.Get();
return individuals;
});
...
}
}

That is good and clear. Every part is utilizing Dependency Injection so nobody is “newing up” an Actor. You may observe additionally that returning the Actors as JSON is implied after we return the IEmumerable<Actor> that comes from actorProvider.Get().

In reality, the entire Actor Module is simply 80 strains so I will embrace it right here:

public class ActorsModule : ICarterModule
{
public void AddRoutes(IEndpointRouteBuilder app)
{
app.MapGet("/actors", (IActorProvider actorProvider, HttpResponse res) =>
{
var individuals = actorProvider.Get();
return individuals;
});

app.MapGet("/actors/{id:int}", (int id, IActorProvider actorProvider, HttpResponse res) =>
{
var individual = actorProvider.Get(id);
return res.Negotiate(individual);
});

app.MapPut("/actors/{id:int}", async (HttpRequest req, Actor actor, HttpResponse res) =>
{
var outcome = req.Validate<Actor>(actor);

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

//Replace the person in your database

res.StatusCode = 204;
});

app.MapPost("/actors", async (HttpContext ctx, Actor actor) =>
{
var outcome = ctx.Request.Validate<Actor>(actor);

if (!outcome.IsValid)
{
ctx.Response.StatusCode = 422;
await ctx.Response.Negotiate(outcome.GetFormattedErrors());
return;
}

//Save the person in your database

ctx.Response.StatusCode = 201;
await ctx.Response.Negotiate(actor);
});

app.MapDelete("/actors/{id:int}", (int id, IActorProvider actorProvider, HttpResponse res) =>
{
actorProvider.Delete(id);
return Outcomes.StatusCode(204);
});

app.MapGet("/actors/obtain", async (HttpResponse response) =>
{
utilizing (var video = new FileStream("earth.mp4", FileMode.Open)) //24406813
{
await response.FromStream(video, "video/mp4");
}
});

app.MapGet("/empty", () => Process.CompletedTask);

app.MapGet("/actors/pattern", () => Process.CompletedTask);

app.MapPost("/actors/pattern", () => Process.CompletedTask);

app.MapGet("/nullable", () => Process.CompletedTask);
}
}

Word the API instance at /actors/obtain that reveals how you can return a file like an MP4. Good and easy. This pattern additionally consists of considerate validation code with FluentValidation extension strategies like ctx.Request.Validate().

Carter is opinionated however surprisingly versatile. You should use two completely different routing APIs, or clear and performant Endpoint routing:

this.Get("/", (req, res) => res.WriteAsync("There isn't any place like 127.0.0.1")).RequireAuthorization();

It even helps OpenAPI out of the field! Carter has an lively Slack in addition to Templates you may add to make your subsequent File | New Mission simpler!

dotnet new -i CarterTemplate
The next template packages can be put in:
CarterTemplate

Success: CarterTemplate::5.2.0 put in the next templates:
Template Title Brief Title Language Tags
--------------- ---------- -------- ------------------------------
Carter Template carter [C#] Carter/Carter Template/NancyFX

There’s a variety of nice innovation occurring within the .NET open supply house proper now.

Carter Source Code

Carter is only one cool instance. Go try Carter on GitHub, give them a Star, strive it out and become involved in open supply!


Sponsor: YugabyteDB is a distributed SQL database designed for resilience and scale. It’s 100% open supply, PostgreSQL-compatible, enterprise-grade, and runs throughout all clouds. Join and get a free t-shirt




About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, guide, father, diabetic, and Microsoft worker. He’s a failed stand-up comedian, a cornrower, and a e-book writer.

facebook
twitter
subscribe
About   Publication

Internet hosting By
Hosted in an Azure App Service










[ad_2]

RELATED ARTICLES

Most Popular

Recent Comments