我想这可能是一个新手问题(我是:))。 在将用户重定向到自定义错误页面时,例如, 404,为了告诉找不到该页面,此重定向的类型为302。
<error statusCode="404" redirect="/Utility/Error404.aspx" />
<error statusCode="400" redirect="/Utility/Error404.aspx" />
是否可以通过Web.config进行此重定向301?
先谢谢所有代码疯子。
答案 0 :(得分:1)
要避免这种情况,请使用正确的HttpCode返回自定义视图:
在您的web.config上,删除错误元素并设置:
<system.webServer>
<httpErrors existingResponse="PassThrough" />
</system.webServer>
在Global.asax上,使用它来渲染自定义的asp.net MVC视图:
protected void Application_Error(object sender, EventArgs e)
{
var ex = HttpContext.Current.Server.GetLastError();
if (ex == null)
return;
while (!(ex is HttpException))
ex = ex.GetBaseException();
var errorController = new ErrorsController();
HttpContext.Current.Response.Clear();
var httpException = (HttpException)ex;
var httpErrorCode = httpException.GetHttpCode();
HttpContext.Current.Response.Write(errorController.GetErrorGeneratedView(httpErrorCode, new HttpContextWrapper(HttpContext.Current)));
HttpContext.Current.Response.End();
}
在你的自定义ErrorsController上,添加它以从asp.net mvc视图生成html视图:
public string GetErrorGeneratedView(int httpErrorCode, HttpContextBase httpContextWrapper)
{
var routeData = new RouteData();
routeData.Values["controller"] = "Errors";
routeData.Values["action"] = "Default";
httpContextWrapper.Response.StatusCode = httpErrorCode;
var model = httpErrorCode;
using (var sw = new StringWriter())
{
ControllerContext = new ControllerContext(httpContextWrapper, routeData, this);
var viewEngineResult = ViewEngines.Engines.FindPartialView(ControllerContext, "Default");
ViewData.Model = model;
var viewContext = new ViewContext(ControllerContext, viewEngineResult.View, ViewData, TempData, sw);
viewEngineResult.View.Render(viewContext, sw);
return sw.ToString();
}
}