80

StackOverflow ポッドキャスト #54で、Jeff は、ルートを処理するメソッドの上の属性を介して、StackOverflow コードベースに URL ルートを登録していると述べています。良いコンセプトのように思えます (Phil Haack がルートの優先度に関して指摘した注意事項があります)。

誰かがこれを実現するためのサンプルを提供できますか?

また、このスタイルのルーティングを使用するための「ベスト プラクティス」はありますか?

4

6 に答える 6

62

更新: これはcodeplexに投稿されました。完全なソース コードとコンパイル済みのアセンブリがダウンロードできます。まだドキュメントをサイトに投稿する時間がないので、現時点ではこの SO 投稿で十分です。

更新: 1) ルートの順序、2) ルート パラメーターの制約、3) ルート パラメーターの既定値を処理するために、いくつかの新しい属性を追加しました。以下のテキストは、この更新を反映しています。

私は実際に MVC プロジェクトでこのようなことをしました (Jeff が stackoverflow でどのように行っているかわかりません)。UrlRoute、UrlRouteParameterConstraint、UrlRouteParameterDefault という一連のカスタム属性を定義しました。これらを MVC コントローラー アクション メソッドにアタッチして、ルート、制約、およびデフォルトを自動的にバインドすることができます。

使用例:

(この例はやや不自然ですが、機能を示していることに注意してください)

public class UsersController : Controller
{
    // Simple path.
    // Note you can have multiple UrlRoute attributes affixed to same method.
    [UrlRoute(Path = "users")]
    public ActionResult Index()
    {
        return View();
    }

    // Path with parameter plus constraint on parameter.
    // You can have multiple constraints.
    [UrlRoute(Path = "users/{userId}")]
    [UrlRouteParameterConstraint(Name = "userId", Regex = @"\d+")]
    public ActionResult UserProfile(int userId)
    {
        // ...code omitted

        return View();
    }

    // Path with Order specified, to ensure it is added before the previous
    // route.  Without this, the "users/admin" URL may match the previous
    // route before this route is even evaluated.
    [UrlRoute(Path = "users/admin", Order = -10)]
    public ActionResult AdminProfile()
    {
        // ...code omitted

        return View();
    }

    // Path with multiple parameters and default value for the last
    // parameter if its not specified.
    [UrlRoute(Path = "users/{userId}/posts/{dateRange}")]
    [UrlRouteParameterConstraint(Name = "userId", Regex = @"\d+")]
    [UrlRouteParameterDefault(Name = "dateRange", Value = "all")]
    public ActionResult UserPostsByTag(int userId, string dateRange)
    {
        // ...code omitted

        return View();
    }

UrlRouteAttribute の定義:

/// <summary>
/// Assigns a URL route to an MVC Controller class method.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class UrlRouteAttribute : Attribute
{
    /// <summary>
    /// Optional name of the route.  If not specified, the route name will
    /// be set to [controller name].[action name].
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// Path of the URL route.  This is relative to the root of the web site.
    /// Do not append a "/" prefix.  Specify empty string for the root page.
    /// </summary>
    public string Path { get; set; }

    /// <summary>
    /// Optional order in which to add the route (default is 0).  Routes
    /// with lower order values will be added before those with higher.
    /// Routes that have the same order value will be added in undefined
    /// order with respect to each other.
    /// </summary>
    public int Order { get; set; }
}

UrlRouteParameterConstraintAttribute の定義:

/// <summary>
/// Assigns a constraint to a route parameter in a UrlRouteAttribute.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class UrlRouteParameterConstraintAttribute : Attribute
{
    /// <summary>
    /// Name of the route parameter on which to apply the constraint.
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// Regular expression constraint to test on the route parameter value
    /// in the URL.
    /// </summary>
    public string Regex { get; set; }
}

UrlRouteParameterDefaultAttribute の定義:

/// <summary>
/// Assigns a default value to a route parameter in a UrlRouteAttribute
/// if not specified in the URL.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class UrlRouteParameterDefaultAttribute : Attribute
{
    /// <summary>
    /// Name of the route parameter for which to supply the default value.
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// Default value to set on the route parameter if not specified in the URL.
    /// </summary>
    public object Value { get; set; }
}

Global.asax.cs への変更:

MapRoute への呼び出しを、RouteUtility.RegisterUrlRoutesFromAttributes 関数への単一の呼び出しに置き換えます。

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        RouteUtility.RegisterUrlRoutesFromAttributes(routes);
    }

RouteUtility.RegisterUrlRoutesFromAttributes の定義:

完全なソースはcodeplexにあります。フィードバックやバグレポートがある場合は、サイトにアクセスしてください。

于 2009-05-21T21:10:05.380 に答える
44

githubまたはnugetから入手できるAttributeRoutingを試すこともできます。

私はプロジェクトの作者なので、これは恥知らずなプラグインです。しかし、私がそれを使用することにあまり満足していない場合は、気をつけてください。あなたもそうかもしれません。github レポジトリwikiには、多くのドキュメントとサンプル コードがあります。

このライブラリを使用すると、多くのことができます。

  • アクションを GET、POST、PUT、および DELETE 属性で装飾します。
  • 複数のルートを 1 つのアクションにマップし、Order プロパティで並べ替えます。
  • 属性を使用してルートのデフォルトと制約を指定します。
  • シンプルな ? でオプションのパラメーターを指定します。パラメータ名の前のトークン。
  • 名前付きルートをサポートするためのルート名を指定します。
  • コントローラーまたはベースコントローラーで MVC 領域を定義します。
  • コントローラーまたはベース コントローラーに適用されるルート プレフィックスを使用して、ルートをグループ化またはネストします。
  • 従来の URL をサポートします。
  • アクションに対して定義されたルート間、コントローラー内、およびコントローラーとベース コントローラー間で、ルートの優先順位を設定します。
  • 小文字のアウトバウンド URL を自動的に生成します。
  • 独自のカスタム ルート規則を定義し、それらをコントローラーに適用して、ボイラープレート属性なしでコントローラー内のアクションのルートを生成します (RESTful スタイルを考えてください)。
  • 提供された HttpHandler を使用してルートをデバッグします。

他にも忘れているものがあると思います。見てみな。ナゲット経由でインストールするのは簡単です。

注: 2012 年 4 月 16 日現在、AttributeRouting は新しい Web API インフラストラクチャもサポートしています。それを処理できるものを探している場合に備えて。ありがとうサブカムラン

于 2011-01-17T19:12:28.360 に答える
9

1. RiaLibrary.Web.dllをダウンロードし、ASP.NET MVC Web サイト プロジェクトで参照します。

2. [Url] 属性を使用してコントローラー メソッドを装飾します。

public SiteController : Controller
{
    [Url("")]
    public ActionResult Home()
    {
        return View();
    }

    [Url("about")]
    public ActionResult AboutUs()
    {
        return View();
    }

    [Url("store/{?category}")]
    public ActionResult Products(string category = null)
    {
        return View();
    }
}

ところで、「?」'{?category}' パラメータは、オプションであることを意味します。ルートのデフォルトでこれを明示的に指定する必要はありません。これは次のようになります。

routes.MapRoute("Store", "store/{category}",
new { controller = "Store", action = "Home", category = UrlParameter.Optional });

3. Global.asax.cs ファイルを更新する

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoutes(); // This does the trick
    }

    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
    }
}

デフォルトと制約の設定方法 例:

public SiteController : Controller
{
    [Url("admin/articles/edit/{id}", Constraints = @"id=\d+")]
    public ActionResult ArticlesEdit(int id)
    {
        return View();
    }

    [Url("articles/{category}/{date}_{title}", Constraints =
         "date=(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])")]
    public ActionResult Article(string category, DateTime date, string title)
    {
        return View();
    }
}

注文の設定方法は?例:

[Url("forums/{?category}", Order = 2)]
public ActionResult Threads(string category)
{
    return View();
}

[Url("forums/new", Order = 1)]
public ActionResult NewThread()
{
    return View();
}
于 2010-02-03T21:06:00.710 に答える
3

この投稿は、DSO の回答を拡張するためのものです。

ルートを属性に変換するときに、ActionName 属性を処理する必要がありました。したがって、GetRouteParamsFromAttribute では次のようになります。

ActionNameAttribute anAttr = methodInfo.GetCustomAttributes(typeof(ActionNameAttribute), false)
    .Cast<ActionNameAttribute>()
    .SingleOrDefault();

// Add to list of routes.
routeParams.Add(new MapRouteParams()
{
    RouteName = routeAttrib.Name,
    Path = routeAttrib.Path,
    ControllerName = controllerName,
    ActionName = (anAttr != null ? anAttr.Name : methodInfo.Name),
    Order = routeAttrib.Order,
    Constraints = GetConstraints(methodInfo),
    Defaults = GetDefaults(methodInfo),
});

また、ルートのネーミングが適切ではないこともわかりました。名前は、controllerName.RouteName で動的に作成されます。しかし、ルート名はコントローラー クラスの const 文字列であり、それらの const を使用して Url.RouteUrl も呼び出します。そのため、属性のルート名をルートの実際の名前にする必要があります。

もう 1 つ行うことは、デフォルト属性と制約属性を AttributeTargets.Parameter に変換して、それらを params に固定できるようにすることです。

于 2009-05-25T15:50:59.613 に答える
0

AsyncController を使用して asp.net mvc 2 で ITCloud ルーティングを機能させる必要がありました。そのためには、ソースの RouteUtility.cs クラスを編集して再コンパイルするだけです。98行目のアクション名から「完了」を取り除く必要があります

// Add to list of routes.
routeParams.Add(new MapRouteParams()
{
    RouteName = String.IsNullOrEmpty(routeAttrib.Name) ? null : routeAttrib.Name,
    Path = routeAttrib.Path,
    ControllerName = controllerName,
    ActionName = methodInfo.Name.Replace("Completed", ""),
    Order = routeAttrib.Order,
    Constraints = GetConstraints(methodInfo),
    Defaults = GetDefaults(methodInfo),
    ControllerNamespace = controllerClass.Namespace,
});

次に、AsyncController で、XXXXCompleted ActionResult を使い慣れた属性UrlRouteUrlRouteParameterDefault属性で装飾します。

[UrlRoute(Path = "ActionName/{title}")]
[UrlRouteParameterDefault(Name = "title", Value = "latest-post")]
public ActionResult ActionNameCompleted(string title)
{
    ...
}

同じ問題を抱えている人に役立つことを願っています。

于 2010-07-22T14:28:16.670 に答える
0

私はこれら 2 つのアプローチを組み合わせて、必要な人のためにフランケンシュタイン バージョンにしました。(オプションの param 表記が気に入りましたが、すべてを 1 つに混在させるのではなく、デフォルト/制約とは別の属性にする必要があるとも考えました)。

http://github.com/djMax/AlienForce/tree/master/Utilities/Web/

于 2010-04-29T15:41:42.427 に答える