如何从自定义MvcRouteHandler回退到路由表中的下一个

本文关键字:路由 下一个 回退 自定义 MvcRouteHandler | 更新日期: 2023-09-27 18:28:07

我有一个自定义MvcRouteHandler,它检查数据库是否存在Url,并将其与一些控制器操作和Id配对。

然而,若这个路由处理程序在数据库中找不到匹配的对,我希望MVC继续尝试路由表中其他定义的路由处理程序。

我该怎么做?

更新:(添加示例代码)

routes.MapRoute(
    name: "FriendlyRoute",
    url: "{FriendlyUrl}").RouteHandler = new FriendlyRouteHandler();

FriendlyRouteHandler是:

public class FriendlyRouteHandler : MvcRouteHandler
{
    private TancanDbContext db = new MyDbContext();
    protected override IHttpHandler GetHttpHandler(System.Web.Routing.RequestContext requestContext)
    {
        if (requestContext.RouteData.Values["FriendlyUrl"] != null)
        { 
            string friendlyUrl = requestContext.RouteData.Values["FriendlyUrl"].ToString();
            //Here, you would look up the URL Record in your database, then assign the values to Route Data
            //using "where urlRecord.Url == friendlyUrl"         
            try
            {
                UrlRecord urlRecord = db.UrlRecords.Single(u => u.URL == friendlyUrl);          
                //Now, we can assign the values to routeData
                if (urlRecord != null)
                {
                    requestContext.RouteData.Values["controller"] = urlRecord.Controller;
                    requestContext.RouteData.Values["action"] = urlRecord.Action;
                    if(urlRecord.EntityId != null)
                    requestContext.RouteData.Values["id"] = urlRecord.ObjectId;
                   }
                }
                else
                {
                    //Here, I want to redirect to next RouteHandler in route Table
                  requestContext.RouteData.Values["controller"] = friendlyUrl;
                }
            }
            catch (Exception ex)
            {               
                //throw;
                //Here too, I want to redirect to next RouteHandler in route Table
                requestContext.RouteData.Values["controller"] = friendlyUrl;
            }
        }
        return base.GetHttpHandler(requestContext);
    }
}

添加此行后,它似乎起作用:

requestContext.RouteData.Values["controller"] = friendlyUrl;

我是幸运还是这是正确的做法?我需要在某个地方使用IRouteConstraint吗?

顺便说一句,我的影响是亚当·里迪克的这篇文章。

如何从自定义MvcRouteHandler回退到路由表中的下一个

您想要使用自定义约束,而不是自定义处理程序。

routes.MapRoute(
    name: "example",
    url: "{friendly}",
    defaults: new { controller = "FriendlyController", action = "Display" },
    constraints: new { friendly = new FriendlyUrlConstraint() }
);

然后约束变成:

public class FriendlyUrlConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        var friendlyUrl = values[parameterName];
        // Your logic to return true/false here
    }
}