C
C#ā€¢15mo ago
wwww

āœ… Endpoints

hi šŸ™‚ can anyone explain why 1 code works and scond no?
app.UseRouting();

app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/products/{id}", async (context) =>
{
var id = Convert.ToInt32(context.Request.RouteValues["id"]);
await context.Response.WriteAsync($"ID {id}");
});
});
app.UseRouting();

app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/products/{id}", async (context) =>
{
var id = Convert.ToInt32(context.Request.RouteValues["id"]);
await context.Response.WriteAsync($"ID {id}");
});
});
app.MapGet("/products/{id}", async (context) =>
{
var id = Convert.ToInt32(context.Request.RouteValues["id"]);
await context.Response.WriteAsync($"ID {id}");
});
app.MapGet("/products/{id}", async (context) =>
{
var id = Convert.ToInt32(context.Request.RouteValues["id"]);
await context.Response.WriteAsync($"ID {id}");
});
also there is third way, but how to get HttpContext here?
app.MapGet("/products/{id}", (string id) => $"Id :{id}");
app.MapGet("/products/{id}", (string id) => $"Id :{id}");
8 Replies
wwww
wwwwOPā€¢15mo ago
ok, i solved it by myself, wasn't working cuz
app.Run(async (context) =>
{
context.Response.StatusCode = 404;
await context.Response.WriteAsync("Page not Found");
});
app.Run(async (context) =>
{
context.Response.StatusCode = 404;
await context.Response.WriteAsync("Page not Found");
});
on the end but still, which is better and conventional way to create endpoints?
Angius
Angiusā€¢15mo ago
The last one is best There's no need to ever use Request and Response Just bind the data you want to get, and return the data you want to return Anything else is giving yourself more work than is necessary for no reason at all Also, don't use Convert.ToInt32, use int.TryParse() Or better yet, with parameter binding... you can just get the integer in the first place No need to convert anything
wwww
wwwwOPā€¢15mo ago
badhun1UA forget i can just
return $"ID: {id}";
return $"ID: {id}";
Angius
Angiusā€¢15mo ago
app.MapGet("/products/{id}", (int id) => $"Id :{id}");
app.MapGet("/products/{id}", (int id) => $"Id :{id}");
yeah
wwww
wwwwOPā€¢15mo ago
Thanks again šŸ—
wwww
wwwwOPā€¢15mo ago
Btw, If I understand it correctly, it should work something like this?
Angius
Angiusā€¢15mo ago
It can, yes
wwww
wwwwOPā€¢15mo ago
badhun1UA
Want results from more Discord servers?
Add your server