Handle Invalid URL in MVC
Asked Answered
P

3

7

How to handle invalid URLs in MVC?

For ex.: When the user enters http://localhost/User/MyProfile instead of http://localhost/User/Profile, it will throw an exception.

How to handle this request?

Perfectible answered 24/5, 2009 at 11:2 Comment(0)
P
12

You need first to add a custom Error page url in the web.config:

<customErrors mode="On" defaultRedirect="~/Error/404" />  

And add a controller to handle the invalid urls:

public class ErrorController:Controller
    {
        [ActionName("404")]
        public ActionResult Error404()
        {
            return View("Error");
        }
    }

And if you want to redirect the user to the home page then you don't need the Error controller just modify the custom error tag:

<customErrors mode="On" defaultRedirect="~/Home/Index" />  
Pruritus answered 24/5, 2009 at 11:46 Comment(1)
Actually, i will need this soon. I helped myself too (favorited this question).Verret
V
1

Did you mean this?

// Show a 404 error page for anything else.
    routes.MapRoute("Error", "{*url}",
    new { controller = "Error", action = "404" }
);
Verret answered 24/5, 2009 at 11:11 Comment(1)
ya exactly like that, but when i used that code, its not redirecting to the specified page. Still showing "The resource cannot be found.". I have added the following in Global.asax.cs: routes.MapRoute("Error", "{*url}", new { controller = "Home", action = "Index" });Perfectible
B
0

I think every request should be redirected to the front controller, so wrap your code inside a try/catch block that will intercept the exception, and maybe you can redirect to the homepage in the catch block or simply raise a 404 error with an exception handler.

What is your server language ?

Binucleate answered 24/5, 2009 at 11:5 Comment(2)
It's tagged asp.net-mvc-routingVerret
Sorry for being irrelevant ^^Cutout

© 2022 - 2024 — McMap. All rights reserved.