Christian Schmitt
Christian Schmitt

Reputation: 892

C# Razor Page disable all /Index Route for Folders?

Hello currently I'm playing with Razor Page and wanted to ask, if there is a possibility to actually do not allow accessing the Index Page directly.

I.e. I have multiple Folders:

now I want to allow people to access them via /Search and /Document, but if anybody calls /Search/Index directly, he should be defaulted, to the "default" 404 handler, is this possible?

Upvotes: 0

Views: 1221

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93183

You can achieve this with a custom Page route action convention. A convention allows you to customise the routes that apply to a page at either the page, area or folder level. To customise the routing for all pages, you can use a folder of /. Here's an example of how you can remove the Index routes:

services
    .AddMvc()
    .AddRazorPagesOptions(options =>
    {
        options.Conventions.AddFolderRouteModelConvention("/", model =>
        {
            var selectorCount = model.Selectors.Count;

            // Go down in reverse order to simplify removing from a list that's being iterated.
            for (var i = selectorCount - 1; i >= 0; i--)
            {
                var selectorTemplate = model.Selectors[i].AttributeRouteModel.Template;

                if (selectorTemplate.EndsWith("Index")) // Perhaps be more specific here.
                    model.Selectors.RemoveAt(i);
            }
        });
    });

Note that for the Index page at the root, the selector to remove is Index (not /Index), whereas for your others it is Page/Index. I've kept it simple in the example, but this will also remove any Pages that have Index as part of their name (it's unlikely this will matter, but it's worth mentioning).

Upvotes: 1

Related Questions