Home > Back-end >  Check if request is made to Razor Page
Check if request is made to Razor Page

Time:05-10

How can I check within middleware code if current request is made to Razor Page not to any other resource (static file, or API)?

All my APIs are located within api folder, so if (!context.Request.Path.StartsWithSegments("/api")) {} filters out APIs, but that will not work for static content as these files and libraries are placed within number of folders what results in number of URL segments.

Could not find any relevant property in context.

CodePudding user response:

First step - place the middleware after app.UseRouting(). Any request for a static file will never reach your middleware because the static files middleware will short circuit the request. Also, after this point, the routing middleware will have selected the endpoint and populated the endpoint metadata. Then you can test the endpoint metadata collection to see if it includes PageRouteMetaData, which tells you that this is a Razor page route:

app.Use((context, next) => {
    var endpoint = context.GetEndpoint();
    if (endpoint != null)
    {
        foreach(var md in endpoint.Metadata)
        {
            if( md is PageRouteMetadata)
            {
                // this is a page route
            }
        }
    }
    return next(context);
});
  • Related