Handle Invalid URL in MVC

折月煮酒 提交于 2019-12-18 10:57:10

问题


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?


回答1:


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" />  



回答2:


Did you mean this?

// Show a 404 error page for anything else.
    routes.MapRoute("Error", "{*url}",
    new { controller = "Error", action = "404" }
);



回答3:


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 ?



来源:https://stackoverflow.com/questions/903537/handle-invalid-url-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!