如何在不更改url的情况下将某人重定向到错误页面



我正在使用C#和asp.net开发一个"错误404"页面。问题是,当用户键入www.example.com/asdasd时,他会被重定向到我的错误404页面,但我希望url保持不变。

例如,用户键入"www.example.com/asdasd",我想保留"www.example.com/sasdasd,而不是"www.example.com/error"(这是我错误重定向的错误404页面的名称(。

这是我的web.config文件中的"自定义错误">

<customErrors mode="On" defaultRedirect="~/error/" redirectMode="ResponseRedirect">
<error statusCode="404" redirect="~/error/" />
</customErrors>

这是我在Global.asax 中的功能

protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex is HttpException && ((HttpException)ex).GetHttpCode() == 404)
{
Response.Redirect("~/error");
}
}

有什么想法或建议吗?

尝试类似的操作:Server.Transfer("~/error"(。这会将请求服务器端"传输"到所需页面,而无需重定向(包括对错误页面的响应和另一个请求(。

Startup.cs类中的Configure方法内部使用UseStatusCodePagesWithReExecute中间件:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{ 
app.UseStatusCodePagesWithReExecute("~/error");
}

最新更新