Route Attribute not working as expected on ComponentBase / Blazor
See original GitHub issueIs there an existing issue for this?
- I have searched the existing issues
Describe the bug
I’m creating a simple component that inherits from a ComponentBase class, and my understanding is that I can use the Route attribute in the base class instead of the @page directive, unfortunately when I do that, I don’t get an error but the page is just blank
BLAZOR COMPONENT:
@inherits EmployeeListBase
<h3>Employee List</h3>
COMPONENT CLASS
using EmployeeManagement.Models;
using Microsoft.AspNetCore.Components;
namespace EmployeeManagement.Web.Pages
{
[Route("/")]
public class EmployeeListBase : ComponentBase
{
public IEnumerable<Employee> Employees { get; set; } = new List<Employee>();
}
}
So basically, this should act as the root page of the razor web, instead, it just displays a blank page, no h3 text, nothing, just blank as follow
Expected Behavior
If I don’t use the Route attribute on the base class and use the @page directive in the component, then it work as expected:
According to the docs at https://docs.microsoft.com/en-us/aspnet/core/blazor/components/?view=aspnetcore-6.0 in the Routing section it states the following:
When a Razor file with an @page directive is compiled, the generated class is given a RouteAttribute specifying the route template.
Thank you so much for all your help! If I’m doing something wrong, PLEASE let me know, thank you.😃
Steps To Reproduce
No response
Exceptions (if any)
No exceptions, just a blank page is returned.
.NET Version
6
Anything else?
No response
Issue Analytics
- State:
- Created 2 years ago
- Comments:7 (4 by maintainers)
Top GitHub Comments
Hi @sipi41. The
[Route]
attribute is defined as not inheritable so if you inherit from a base class that has a route attribute set, it won’t be honored on the descending class. This is because as @TanayParikh explained this would lead to ambiguity, as you can end up with multiple classes having the same route.It’s perfectly fine to inherit from a base class, but you should add the
@Page
(in razor) or[Route]
in .cs attribute only to the top-level component. (which you could call a Page, a Blazor component to which you can route to, like the/counter
example on the https://blazor-university.com/components/ websiteThe Blazor routing code will ignore the [Route] attribute when set on a descending class, and that is what you are experiencing. Code here
@MariovanZeist Marvelously explained! this is why I love the way where all code is just there… it’s hard for us to remember that X thing is not transferable or inheritable… 😦 Thank you Mario! you are the hero of the week!