2

Urlが存在するかどうかをデータベースをチェックし、それをコントローラーアクションとIDとペアにするカスタムMvcRouteHandlerがあります。

ただし、このルート ハンドラーがデータベース内で一致するペアを見つけることができない場合、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