Asp网404页面参数
我正在开发asp网络mvc 5中的新网站。我想创建自定义的404页面,用户试图访问旧网址将被重定向。问题是我想为这个错误页面创建视图并从url中获取参数,试图识别用户试图访问的产品。但我还没有找到解决方案如何创建它。所有编辑webconfig的示例都是这样的:Asp网404页面参数
<defaultRedirect="~/Errors/NotFound" mode="Off">
<error statusCode="404" redirect="~/Errors/NotFound" />
</customErrors>
不会传递参数。我试图禁用自定义错误,并在Global.asax中的变化:
public void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
if (httpException != null)
{
if(httpException.GetHttpCode() == 404)
{
var rd = new RouteData();
rd.Values["controller"] = "Errors";
rd.Values["action"] = "NotFound";
rd.Values.Add("queryString", HttpContext.Current.Request.Url.AbsolutePath);
IController c = new ErrorsController();
c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
}
}
}
但它仍然会返回非标准错误页面
你可以试试这个:
RouteValueDictionary rvd = new RouteValueDictionary(){
{
{ "Controller", "Errors" },
{ "Action", "NotFound" }
};
rvd["queryString"] = HttpContext.Current.Request.Url.AbsolutePath;
Response.RedirectToRoute(rvd);
希望这说得通。
你应该这样编辑web.config文件:
<system.web>
<customErrors mode="On" defaultRedirect="~/Error">
<error redirect="~/Error/NotFound" statusCode="404" />
</customErrors>
</system.web>
解决的办法是比我想象的更容易。当你在webconfig
<defaultRedirect="~/Errors/NotFound" mode="On">
<error statusCode="404" redirect="~/Errors/NotFound" />
</customErrors>
设置自定义错误的请求的URL将在查询字符串所以它是anough得到这样的:
public ActionResult NotFound()
{
var requestedString = Request.QueryString["aspxerrorpath"];
return View();
}
xml看起来不正确。最上面的元素应该是:'
另外还有一件事,在你对SamGhatak的回答发表评论时,你会提及在期待404时返回状态代码200.但我认为你的方法会也返回状态码200.有几种方法可以返回特定的状态码。看看这个问题:http://stackoverflow.com/questions/2948484/how-to-get-mvc-action-to-return-404 –
@LarsKristensen,关于404状态。 Asp网络核心manualy设置302错误,当使用webconfig,这是可怕的。我查看了你发布的链接,但是我不知道应该在哪里写404异常,而不是asp网络核心抛出的302错误 – dantey89
我还没有看到重定向到一个错误页面的那种方式之前。你尝试过使用'return RedirectToAction(“NotFound”,“Errors”);'? –
此外,如果您只是将错误页面输入到“http:// localhost:57623/Errors/NotFound”,会发生什么? –
我不相信传递参数的作用(至少不是在每种情况下 - 请记住,如果错误发生在IIS中,重定向发生在甚至调用ASP.NET之前)。但是,[本文](https://dusted.codes/demystifying-aspnet-mvc-5-error-pages-and-error-logging)会覆盖这些选项,因为它们适用于自定义页面和日志记录。请注意,传递参数并不常见,因为最佳做法是记录错误并为每个状态代码显示一个通用页面,否则黑客可以使用网站的输出(参数)来查找漏洞。 – NightOwl888