如果您想在显示错误 404 的同时“保持”在同一条路线上:
创建一个类NotFoundListener.cs
public class NotFoundListener
{
public Action OnNotFound { get;set; }
public void NotifyNotFound()
{
if(NotifyNotFound != null)
{
OnNotFound.Invoke();
}
}
}
将其作为作用域服务注入
builder.Services.AddScoped<NotFoundListener>();
在你的MainLayout.razor
@inherits LayoutComponentBase
@inject NotFoundListener nfl;
<PageTitle>ImportTesting</PageTitle>
<div class="page">
<div class="sidebar">
<NavMenu />
</div>
<main>
<div class="top-row px-4">
<a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a>
</div>
<article class="content px-4">
@if (notFound)
{
<h1>Could not find the content you are looking for</h1>
}else
{
@Body
}
</article>
</main>
</div>
@code{
private bool notFound;
protected override void OnInitialized() => nfl.OnNotFound += SetNotFound;
void SetNotFound()
{
notFound = true;
StateHasChanged();
}
}
并且在你要引发 404 的页面中:
protected override void OnInitialized()
{
if (project == null)
{
nfl.NotifyNotFound();
}
}
这将:
- 让您在浏览器中保持同一路线
- 不导航到任何地方
- 确保每一页都没有 if else
(我用Action来处理事件,不是最好的使用方式,但是让代码更容易阅读)
现在,
- 您可以为不同的页面设置不同的事件侦听器。
- 您可以根据具体需要创建不同的布局。
- 如果您只想在某些页面而不是所有页面上应用此功能,请添加
'route' 事件的参数并在 MainLayout 上检查它。
如果您想重复使用标准错误页面:
您的错误页面在您的 App.razor 中定义
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
您可以创建自己的NotFoundComponent.razor 组件
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
您更新后的App.razor 如下所示:
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<NotFoundComponent/>
</NotFound>
</Router>
然后你可以创建一个简单地引用同一个组件的页面
NotFoundPage.razor
@page "/NotFound"
<NotFoundComponent />
然后使用您的页面重定向如下
来自您的 OnInitialized()
@page "/{projectname}"
<!-- HTML Here -->
@code {
[Parameter]
public string ProjectName {get; set;}
private UpdateProjectViewModel Project;
protected override void OnInitialized()
{
var project = Repository.Get(ProjectName);
if (project == null)
{
NavigationManager.NavigateTo("/NotFound");
}
Project = new UpdateProjectViewModel(project));
}
}