Reputation: 105
Just practicing with ASP.NET CORE
Middleware I have this code below. I reach it with address http://localhost:5000/location and it outputs :
Buffalo in USA // that's correct, coming from MessageOptions class.
Status Code: 200
my expectation was that the flow be like this:
Print the City and Country name because the path has /location
in it.
Then with next()
go to print Status Code 200 which also has a next()
so I was hoping after that it goes to last one and print the Hello World
too but it does NOT go to last one to print Hello World.
My question is WHY?
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IOptions<MessageOptions> options)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// conditional branching in middleware.
app.MapWhen(context => context.Request.Query.ContainsKey("branch"), branch => { branch.UseMiddleware<QueryStringMiddleWare>(); });
app.Use(async (context, next) =>
{
if (context.Request.Path == "/location")
{
MessageOptions opts = options.Value;
await context.Response.WriteAsync($"{opts.CityName} in {opts.CountryName}");
await next();
}
else
{
await next();
}
});
app.Use(async (context, next) =>
{
await context.Response.WriteAsync($"\n Status Code: {context.Response.StatusCode} \n");
await next();
});
app.Use(async (context, next) =>
{
if (context.Request.Method == HttpMethods.Get && context.Request.Query["custom"] == "true")
{
await context.Response.WriteAsync("Hello from Inline Middleware \n");
}
await next();
});
app.UseMiddleware<QueryStringMiddleWare>();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World From Starutp.cs! \n");
});
});
}
Upvotes: 0
Views: 189
Reputation: 15663
The last one matches requests like HTTP GET http://localhost:5000/
and does not match requests like HTTP GET http://localhost:5000/location
.
Upvotes: 2