gpt4 book ai didi

c# - 如何在发生 404 重定向时添加额外的查询字符串参数

转载 作者:行者123 更新时间:2023-12-02 22:36:22 26 4
gpt4 key购买 nike

我们目前正在为我们的网络应用程序使用 404 错误的自定义错误页面。当重定向发生时,aspxerrorpath 包含用户试图访问的路径。是否可以在 Global.asax 中捕获 Application_Error 中的错误并在重定向发生之前将新参数附加到查询字符串?我想附加用户请求的主机。

我的理解是 IIS 处理 404 重定向并将 aspxerrorpath 参数附加到 404 重定向,我想在它发生之前拦截它并将另一个参数附加到查询字符串。

更多信息:我们在 CMS 中有多个站点,因此请求的 url 不会总是 www.example.com 但 404 重定向将始终是 www.example.com

目前:用户请求 www.example.com/fakepage.aspx 并被重定向到...

www.example.com/404.aspx?aspxerrorpath=/fakepage.aspx

我想要的:用户请求 www.example.com/fakepage.aspx 并被重定向到...

www.example.com/404.aspx?aspxerrorpath=/fakepage.aspx&aspxerrorhost=example.com

解决方案:我最终实现了自定义 HttpModule(请参阅下面的答案)。我只是想传递一篇优秀的文章来解释如何做到这一点。 http://helephant.com/2009/02/11/improving-the-way-aspnet-handles-404-requests/

最佳答案

尝试将以下代码放入您的 global.asax 文件中:

void Application_Error(object sender, EventArgs e)
{
string host = Context.Request.Url.Host;
string redirectUrl = string.Format("~/Error.html?aspxerrorpath={0}&aspxerrorhost={1}", Server.UrlEncode(Context.Request.Path), Server.UrlEncode(host));
Response.Redirect(redirectUrl);
}

这实质上是创建您自己的错误处理程序以重定向到错误页面,这更加灵活,因为您可以向 url 添加您希望的任何查询参数。

要使用此方法,您将无法以正常方式在 web.config 文件中配置重定向。但是,您可以使用文件的 appSettings 部分,然后像这样读取值:

Web.config 文件

<appSettings>
<add key="redirectPath" value="valueGoesHere"/>
</appSettings>

C# 错误处理程序

string redirectPath = System.Configuration.ConfigurationManager.AppSettings["redirectPath"];

编辑:

此外,如果您需要根据 http 错误代码重定向到不同的页面,请在错误处理程序中使用以下代码:

HttpException exception = Server.GetLastError() as HttpException;
int errorCode = -1;

if(exception != null)
{
errorCode = exception.GetHttpCode();
}

switch (errorCode)
{
case 404:
// Redirect here
break;
default:
// Redirect here
break;
}

关于c# - 如何在发生 404 重定向时添加额外的查询字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11396235/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com