Search code examples
asp.net-corerazor-pagesasp.net-core-7.0

Razor Page page model file without corresponding content file


I'm using Razor Pages. Sometimes I need a page model file without the corresponding content file. But I must nonetheless specify a route for that page, and so define a content file anyway, just for the @page "/foo".

Example: the user clicks a link in a confirmation email, which leads to a token confirmation callback page /confirm. That redirects to various other pages based on whether the token was valid; e.g. /login, /resend-token, /error. So the page itself never renders content.

Confirm.cshtml

@page "/confirm"
@model ConfirmModel
@{ throw new InvalidOperationException("This page should never be rendered."); }

Confirm.cshtml.cs

public class ConfirmModel : PageModel
{
  public IActionResult OnGet()
  {
    // handles various scenarios; each redirects somewhere else
    // never returns `Page()`
    // ...
  }
}

Is there a way to avoid that useless Confirm.cshtml content file?


Solution

  • If you need endpoints in a Razor Pages app that have no corresponding UI, you can use a standard MVC controller or a minimal API request handler (https://www.mikesdotnetting.com/article/358/using-minimal-apis-in-asp-net-core-razor-pages)

    For example, in your Program.cs file, you would add this:

    app.MapGet("/confirm", async (HttpContext context, [FromServices]IMyService service ) => {
        await service.PerformSomeTaskAsync();
        context.Response.Redirect("/some-url");
    });