处理MVC中的无效URL

Pra*_*sad 7 model-view-controller asp.net-mvc invalid-url asp.net-mvc-routing

如何处理MVC中的无效URL?

例如:当用户输入http:// localhost/User/MyProfile而不是 http:// localhost/User/Profile时,它将引发异常.

如何处理这个请求?

小智 12

您首先需要在web.config中添加自定义错误页面URL:

<customErrors mode="On" defaultRedirect="~/Error/404" />  
Run Code Online (Sandbox Code Playgroud)

并添加一个控制器来处理无效的URL:

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

如果您想将用户重定向到主页,那么您不需要错误控制器只需修改自定义错误标记:

<customErrors mode="On" defaultRedirect="~/Home/Index" />  
Run Code Online (Sandbox Code Playgroud)