Let's say I have a razor page application, and there is a razor page "Product.cshtml", how can I see "Product.cshtml" string in the HttpContext object (assuming I can access the HttpContext object in the middleware before endpoint middleware as the code below shows)? I tried to use EndpointHttpContextExtensions.GetEndpoint(HttpContext) extension method, still couldn't find anything that might contain "Product.cshtml".
// startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
app.UseRouting();
app.UseMiddleware<GetEndPointMiddleWare>();
app.UseEndpoints(endpoints => {
endpoints.MapRazorPages();
});
}
public class GetEndPointMiddleWare
{
private RequestDelegate next;
public QueryStringMiddleWare(RequestDelegate nextDelegate) {
next = nextDelegate;
}
public async Task Invoke(HttpContext context) {
...
await next(context);
// I want to print "Product.cshtml" here
// var endpoint = EndpointHttpContextExtensions.GetEndpoint(context); // <---- didn't find any property that has the string I want
}
}
The path to the page is within the endpoint metadata as part of a PageActionDescriptor object, so that could be accessed and parsed. An example of middleware that inspects the page path:
// Startup.cs -> Configure()
app.UseRouting();
app.Use(next => context =>
{
var endpoint = context.GetEndpoint();
if (endpoint is null)
{
return Task.CompletedTask;
}
if (endpoint.Metadata.FirstOrDefault(i => i is PageActionDescriptor) is PageActionDescriptor pageDescriptor)
{
string pagePath = pageDescriptor.RelativePath;
Console.WriteLine($"Page path: {pagePath}"); // '/Pages/Product.cshtml'
}
return Task.CompletedTask;
});
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapDefaultControllerRoute();
});
(Adapted from docs example)