0

ArticleView を返す Index メソッドを持つ ArticleController という名前のコントローラーがあります。これは機能します。

ただし、Article/someText Article/fileNanme Article/etc のような URL の Article/ 以降のテキストは処理できるようにしたいです。

これは、次のように実装することで簡単になると思いました。

// GET: /Article/{text}
public ActionResult Index(string someText)
{
    ...
}

これはうまくいきません。何か案は?

アップデート:

ルートを見る:

    routes.MapRoute(
        name: "Articles",
        url: "Article/{*articleName}",
        defaults: new { controller = "Article", action = "Article", id= UrlParameter.Optional }
        ,
        constraints: new { therest = @"\w+" }
    );

 routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new {  controller="Home", action = "Index", id = UrlParameter.Optional }
    );

ArticleController メソッドを参照してください。

public ActionResult Index()
    {
       ...
    }


    public ActionResult Article(string articleName)
    {
       ...
    }
4

3 に答える 3

1

このように、キャッチオールパラメーターをルートに追加できます

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{*therest}",
                defaults: new { controller = "Home", action = "Index" }
            );

アスタリスクに注意してください。therestこれは「キャッチオール」パラメータとしてマークされ、URL の残りのすべてのセグメントに一致します。

あなたの行動では、あなたは

public ActionResult Article(string therest)
{
  /*...*/
}

これは、「Home/Article/This/Is/The/Rest」のような URL に対しても機能します。この場合therest、値は「This/Is/The/Rest」になります。

URL のコントローラー部分を完全に省略したい場合は、次のようになります。

routes.MapRoute(
                name: "Default",
                url: "Article/{*therest}",
                defaults: new { controller = "Home", action = "Index" }
            );

「Article/ThisIs/JustSomeText」などの URL に一致します。

therest少なくとも何かを含めたい場合は、ルーティング制約を追加できます。

routes.MapRoute(
                name: "Default",
                url: "Article/{*therest}",
                defaults: new { controller = "Home", action = "Index" },
                constraints: new { therest = @"\w+" }
            );

therest制約は、ルートが一致するために一致する必要がある正規表現です。

Stephen Walther のルーティングとキャッチオール パラメータに関するすばらしい記事があります。Stephen Walther もまた、ルーティングの制約に関する記事をここに掲載しています。

于 2013-08-04T20:20:38.470 に答える
0

あなたが言及したURLを使用するには、ルートを定義する必要があります。最新の MVC4 の場合、routes ファイルはこのディレクトリ App_Start/RouteConfig.cs にあります。

デフォルトルートに関するこの新しいルートを追加します。

routes.MapRoute(
            name: "Custom",
            url: "Article/{someText}",
            defaults: new { controller = "Article", action = "Index" }
        );

今すぐ URL を読み込んでみてください。今すぐ動作するはずです。

于 2013-08-04T20:22:05.260 に答える