如果在控制器中没有找到操作,MVC路由到索引

本文关键字:操作 路由 索引 MVC 控制器 如果 | 更新日期: 2023-09-27 18:03:40

我的应用程序中有一个多页面表单,因此,每个方法发布到下一个。这很好,除非您试图访问用[HttpPost]装饰的方法的URL。

是否有任何方法可以将此特定控制器内的所有404请求路由到Index方法?

如果在控制器中没有找到操作,MVC路由到索引

我将把这个作为一个答案,因为我不能添加它作为评论

看看这个链接,它可能对你有帮助

你可以在OnActionExecuting中捕获错误,在那里你可以重定向

也正如在本页的回答中提到的,你可以处理Controller.OnException

public class BaseController: Controller
{
    protected override void OnException(ExceptionContext filterContext)
    {
        // Bail if we can't do anything; app will crash.
        if (filterContext == null)
            return;
            // since we're handling this, log to elmah
        var ex = filterContext.Exception ?? new Exception("No further information exists.");
        LogException(ex);
        filterContext.ExceptionHandled = true;
        var data = new ErrorPresentation
            {
                ErrorMessage = HttpUtility.HtmlEncode(ex.Message),
                TheException = ex,
                ShowMessage = !(filterContext.Exception == null),
                ShowLink = false
            };
        filterContext.Result = View("Index", data); // to redirect to the index page
    }
}

之后,你可以让所有的控制器从BaseController继承