I guess this may be a novice question ( Which I am :) ). While redirecting user to custom error page, for e.g. 404, to tell that page wasn't found, the type of this redirect is 302.
<error statusCode="404" redirect="/Utility/Error404.aspx" />
<error statusCode="400" redirect="/Utility/Error404.aspx" />
Is it possible to make this redirect 301 through Web.config?
Thanks in advance to you all code maniacs.
To avoid this, and returning custom view with correct HttpCode :
On your web.config, remove error elements and set :
<system.webServer>
<httpErrors existingResponse="PassThrough" />
</system.webServer>
On your Global.asax, use this to render custom asp.net MVC View :
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();
}
On your custom ErrorsController, add this to generate html view from asp.net mvc view :
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With