11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ASP.NET MVCでRouteを設定する

Last updated at Posted at 2014-02-05

ASP.NET MVCで「/tags/tagName」といったURLを使えるように設定してみます。

RouteConfigの設定

RouteConfig.csのRegisterRoutesメソッドの routes.MapRoute(name: "Default"... の前に以下のコードを追加します。

RouteConfig.cs
routes.MapRoute(
    name: "TagDetail",
    url: "tags/{tagName}",
    defaults: new { controller = "Tag", action = "Detail" }
);

これで例えば「/tags/tag1」といったURLに対して、
TagControllerのDetailメソッドが、パラメタtagNameに"tag1"を渡されて、呼び出されます。

「.」を許す

タグ名に「.」を含められるようにしたい場合、さらに設定が必要です。
デフォルトの設定では「.」を含むURLは404 Not Foundになってしまいます。
これを「/tags/」以下のPathには「.」も含められるようにするには、
以下の記述をWeb.configのsystem.webServer/handlers内に加えます。

Web.config
<add name="TagsUrlHandler"
     path="/tags/*"
     verb="*"
     type="System.Web.Handlers.TransferRequestHandler"
     preCondition="integratedMode,runtimeVersionv4.0" />

これで「/tags/ASP.NET」といったURLに対しても、
RouteConfig.csで指定したアクションが呼び出されるようになります。

11
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?