2

我有一个自定义的 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 吗?

顺便说一句,我的影响是Adam Riddick 的这篇文章

4

1 回答 1

4

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

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
    }
}
于 2018-03-20T19:09:34.270 回答