Minimal APIs at a look in .NET 6

0
199

[ad_1]


imageDavid Fowler would not have a weblog. I feel the psychic weight of getting a weblog would stress him out. Thankfully, David’s ‘weblog’ is definitely hidden in his prolific GitHub commits and GitHub Gists.

David has been quietly creating¬† a tremendous piece of documentation for Minimal APIs in .NET 6. Sooner or later when it is launched we’ll work with David to get all the pieces promoted to formal documentation, however so far as I am involved if he’s slapping the keyboard anyplace and it exhibits up anyplace with a URL then I am proud of the end result!

Let’s discover a bit right here and I encourage you to head over to the principle Gist right here.

To begin, we see how simple it’s to make a .NET 6 (minimal) app to say Good day World over HTTP on localhost:5000/5001

var app = WebApplication.Create(args);

app.MapGet("/", () => "Good day World");

app.Run();

Pretty. It is principally nothing. Can I do extra HTTP Verbs? Sure.

app.MapGet("/", () => "This can be a GET");
app.MapPost("/", () => "This can be a POST");
app.MapPut("/", () => "This can be a PUT");
app.MapDelete("/", () => "This can be a DELETE");

What about different verbs? Multiple?

app.MapMethods("/options-or-head", new [] { "OPTIONS", "HEAD" }, () => "That is an choices or head request ");

Lambda expressions, not objects, are our “atoms” that we construct molecules with on this world. They’re the constructing blocks.

app.MapGet("/", () => "That is an inline lambda");

var handler = () => "This can be a lambda variable";

app.MapGet("/", handler)

However it’s only a perform, so you may arrange issues nonetheless you need!

var handler = new HelloHandler();

app.MapGet("/", handler.Good day);

class HelloHandler
{
public string Good day()
{
return "Good day World";
}
}

You may seize route parameters as a part of the route sample definition.

app.MapGet("/customers/{userId}/books/{bookId}", (int userId, int bookId) => $"The consumer id is {userId} and ebook id is {bookId}");

Route constraints are affect the matching habits of a route. See how that is so as of specificity:

app.MapGet("/todos/{id:int}", (int id) => db.Todos.Discover(id));
app.MapGet("/todos/{textual content}", (string textual content) => db.Todos.The place(t => t.Textual content.Incorporates(textual content));
app.MapGet("/posts/{slug:regex(^[a-z0-9_-]+$)}", (string slug) => $"Submit {slug}");

Attributes can be utilized to explicitly declare the place parameters needs to be certain from! So you may choose and select from throughout!

utilizing Microsoft.AspNetCore.Mvc;

app.MapGet("/{id}", ([FromRoute]int id,
[FromQuery(Name = "p")]int web page,
[FromServices]Service service,
[FromHeader(Name = "Content-Type")]string contentType) => { });

I can customise the response:

app.MapGet("/todos/{id}", (int id, TodoDb db) => 
db.Todos.Discover(id) is Todo todo
? Outcomes.Okay(todo)
: Outcomes.NotFound()
);

Here is a cool instance of taking a file add and writing it to an area file. Good and clear.

app.MapGet("/add", async (HttpRequest req) =>
{
if (!req.HasFormContentType)
{
return Outcomes.BadRequest();
}

var kind = await req.ReadFormAsync();
var file = kind.Information["file"];

if (file is null)
{
return Outcomes.BadRequest();
}

var uploads = Path.Mix(uploadsPath, file.FileName);
await utilizing var fileStream = File.OpenWrite(uploads);
await utilizing var uploadStream = file.OpenReadStream();
await uploadStream.CopyToAsync(fileStream);

return Outcomes.NoContent();
})
.Accepts<IFormFile>("multipart/form-data");

Go try this nice (and rising) on-line useful resource to study .NET 6 minimal APIs.


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. Enroll and get a free t-shirt.




About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, marketing consultant, father, diabetic, and Microsoft worker. He’s a failed stand-up comedian, a cornrower, and a ebook creator.

facebook
twitter
subscribe
About   E-newsletter

Internet hosting By
Hosted in an Azure App Service










[ad_2]