asp.net-mvc - 在抛出 404 之前有没有办法避免 302 重定向?
问题描述
在 MVC 中,在 statusCode 404 上定义了 customErrors 路径,该路径按预期工作,但在 404 之前返回状态代码 302。
我们可以避免临时重定向吗?
解决方案
What you're looking for is the attribute redirectMode="ResponseRewrite" on the customErrors tag of the web.config. Unfortunatly it only works with aspx, and doesn't work for ASP.NET MVC.
So to achieve what you want in MVC you have to handle the error to write the response that you want.
in Global.asax.cs :
protected void Application_Error(object sender, EventArgs e)
{
HttpException httpException = Server.GetLastError().GetBaseException() as HttpException;
if (httpException != null)
{
if (httpException.GetHttpCode() == 404)
{
RouteData routeData = new RouteData();
Response.Clear();
Server.ClearError();
routeData.Values.Add("controller", "Errors");
routeData.Values.Add("action", "Error404");
var requestContext = new RequestContext(new HttpContextWrapper(Context), routeData);
var controller = ControllerBuilder.Current.GetControllerFactory().CreateController(requestContext, "Errors");
controller.Execute(requestContext);
}
}
}
this code will handle the 404 error, and call the action Error404 on the ErrorsController without doing a redirect.
推荐阅读
- javascript - 为什么我的 onkeydown 函数只能使用一次?
- python - 在 Python 中以 y =a*x+b 的形式学习线性模型
- c# - c# 中的 using 语句不会关闭连接。为什么?
- json - 将文件保存为 .pem 从 powershell 5.1 编码为 utf8noBOM 并使用 openssl 读取它会引发错误
- elasticsearch - 如何在 elasticsearch 嵌套中添加条件属性以创建索引?
- mongodb - 仅通过有效负载更新
- r - 我可以将标记化字符串列表组合到 R 中的数据框吗?
- javascript - 无法通过 Google Cloud Platform 中的 api 为角色/编辑用户添加用户
- node.js - 使用节点js上传文件时s3触发事件不起作用
- python - 如何在同一行打印列表值?