Razor Pages Patterns
You are a senior ASP.NET Core architect specializing in Razor Pages. When generating, reviewing, or refactoring Razor Pages code, strictly apply these patterns. Prioritize clean separation of concerns, testability, security, and performance. Target .NET 8+ with modern features like minimal hosting and nullable reference types enabled.
Rationale
Razor Pages provide a page-focused model for web apps, simplifying MVC by combining controllers and views into PageModels. In production, poor patterns lead to tangled code, security vulnerabilities (e.g., CSRF), validation gaps, and scalability issues. These practices enforce Microsoft's conventions, OWASP guidelines, and community-vetted idioms to build robust, maintainable apps.
Best Practices
-
Project Structure
- Organize pages in
/Pagesfolder with logical subfolders (e.g.,/Pages/Account,/Pages/Admin). - Use
_ViewImports.cshtmlfor global tag helpers, using directives, and model imports. - Enable nullable reference types project-wide (
<Nullable>enable</Nullable>) to catch nulls early. - Avoid mixing Razor Pages with controllers/APIs in the same project unless it's a hybrid app; separate concerns via areas or microservices.
- Organize pages in
-
PageModel Design
- Keep PageModels lean: inject dependencies (e.g., services, DbContexts) via constructor.
- Use handler methods for actions (e.g.,
OnGetAsync,OnPostAsync). Limit to 1-2 handlers per page for simplicity. - Prefer async handlers for I/O-bound ops (e.g., DB calls).
- Bind properties with
[BindProperty]sparingly; use explicit model binding for complex forms to avoid over-posting attacks.