el peregrino
el peregrino

Reputation: 791

How to make razor page available only in development?

I have an API that also includes several Razor pages. I'd like to make one of those razor pages available only during development as it is some support tool.

What is the best way to do that? Use IPageFilter? Use Condition attribute in csproj file to exclude the content file?

Any working example is appreciated.

Upvotes: 2

Views: 1195

Answers (1)

Michael
Michael

Reputation: 1276

If only one page has to be blocked, a filter can be defined directly in the Razor Page:

public class MyRazorPageModel : PageModel
{
    private readonly IWebHostEnvironment _env; // using Microsoft.AspNetCore.Hosting;

    public MyRazorPageModel (IWebHostEnvironment env) // Injected from ASP.NET Core
    {
        _env = env;
    }

    public void OnGet()
    {
    }

    public override void OnPageHandlerExecuting(PageHandlerExecutingContext context)
    {
        // ASPNETCORE_ENVIRONMENT is not set to "Development" in Properties/launchSettings.json: return 404.
        if (!_env.IsDevelopment())  // using Microsoft.Extensions.Hosting;
        {
            context.Result = NotFound();
        }
    }
}

If you want to check debug or relase mode, you can use #if DEBUG.

Upvotes: 3

Related Questions