I'm developing an ASP.NET MVC 5 app with .NET Framework 4.5.1 and C#.
I want to redirect to home/index when an user tries to get access to a resource that doesn't exist.
Yes, there are a lot of questions about how to solve this problem. I read them, but their solutions don't work for me.
Now, I'm trying this on web.config:
<system.webServer>
<httpErrors>
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" path="~/Home/Index" responseMode="Redirect" />
</httpErrors>
</system.webServer>
But, when I try to access this URL, http://host01/Views/ConnectBatch/Create.cshtml, I get the default 404 page.
Maybe the problem is in path="~/Home/Index" but I tried with path="~/" and I get the same default 404 page.
Any idea?
There lot of thread in stackoverflow but my case ..working this
<customErrors mode="On" >
<error statusCode="404" redirect="/404.shtml" />
</customErrors>
Orginal Thread
Or
You Should Handle The error in Code behind Like this (global.asax)
public class MvcApplication : HttpApplication
{
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == 404)
{
Response.Clear();
var routedata= new RouteData();
routedata.DataTokens["area"] = "ErrorArea"; // In case controller is in another area
routedata.Values["controller"] = "Errors";
routedata.Values["action"] = "NotFound";
IController c = new ErrorsController();
c.Execute(new RequestContext(new HttpContextWrapper(Context), routedata));
}
}
}
In your error Controller Like this
public sealed class ErrorsController : Controller
{
public ActionResult NotFound()
{
ActionResult result;
object model = Request.Url.PathAndQuery;
if (!Request.IsAjaxRequest())
result = View(model);
else
return RedirectToAction("Index", "HomeController");
}
}
Orginal Thread
This is how I have solved my problem. Maybe others answers can solved it but I have tested a few of them (I have added a comment on answers that I've tested saying that, that answer doesn't work for me).
I have added this in Web.config inside <system.web>:
<customErrors mode="On" redirectMode="ResponseRedirect">
<error statusCode="404" redirect="~/"/>
</customErrors>
I want to redirect to /Home/Index when an user doesn't find a resource.
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