VirtualPathDataオブジェクトを利用して URLルーティングのリンク先URLを生成する方法を紹介します。
概要
ASP.NETでURLルーティングを利用する場合、単純にURLをハードコーディングするとうまく動作しないなどの不具合が発生する場合があります。(うまく動かない動作の詳細については
こちらの記事を参照してください。)
この記事では、VirtualPathDataオブジェクトを利用してURLルーティングのURLを生成する手順を紹介します。
プログラム例
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Handle.aspx.cs" Inherits="AspNetRoutingCreateLink.Handle" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label><br />
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</div>
</form>
</body>
</html>
デザイナ画面では下図になります。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Routing;
namespace AspNetRoutingCreateLink
{
public partial class Handle : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string act = (string)Page.RouteData.Values["action"];
string tgt = (string)Page.RouteData.Values["target"];
Label1.Text = act;
Label2.Text = tgt;
RouteValueDictionary parameters = new RouteValueDictionary
{
{"action", "run" },
{ "target", "penguin" }
};
VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, "MyRoute01", parameters);
Literal1.Text=string.Format("<a href=\"{0}\">Link</a>", vpd.VirtualPath);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Routing;
namespace AspNetRoutingCreateLink
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteValueDictionary default_dic = new RouteValueDictionary();
default_dic.Add("action", "run");
default_dic.Add("target", "duck");
RouteTable.Routes.MapPageRoute("MyRoute01", "{action}/{target}", "~/Handle.aspx", true, default_dic);
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
}
}
解説
Global.asaxでRoutesに設定したルーティングは下記のコードです。ルーティング名は"MyRoute01"であり、action, target の2つのパラメータがあります。
RouteValueDictionary default_dic = new RouteValueDictionary();
default_dic.Add("action", "run");
default_dic.Add("target", "duck");
RouteTable.Routes.MapPageRoute("MyRoute01", "{action}/{target}", "~/Handle.aspx", true, default_dic);
URLの生成は、Handle.aspx.cs の下記コードにて処理します。
RouteValueDictionary オブジェクトを作成し、パラメーターとそのパラメーターに設定する値の組を作成します。下記のコードでは actionパラメーターに"run"、targetパラメーターに"penguin" を設定します。
続いて、VirtualPathData を取得します。RouteTable.Routes オブジェクトのGetVirtualPath()メソッドを呼び出します。今回は第一引数をnullとし、第二引数にルーティング名を与え、第三引数にURLのパラメーターの値が設定されたRouteValueDictionary を与えます。
RouteValueDictionary parameters = new RouteValueDictionary
{
{"action", "run" },
{ "target", "penguin" }
};
VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, "MyRoute01", parameters);
URLの文字列はVirtualPathData オブジェクトの VirtualPath プロパティで取得できます。取得した値を利用してLiteralにリンクのHTMLを設定しています。
Literal1.Text=string.Format("<a href=\"{0}\">Link</a>", vpd.VirtualPath);
実行結果
プロジェクトを実行し、Webブラウザが表示されますので
http://localhost:51198/MyApp/walk/duck
にアクセスします。下図の画面が表示されます。
[Link]のリンク先を確認します。リンク先のURLは
http://localhost:51198/MyApp/run/penguin
になり、正しいリンク先になっています。
トレイリングスラッシュがあるURL
http://localhost:51198/MyApp/jump/fox/
にアクセスします。下図の画面が表示されます。
[Link]のリンク先を確認します。リンク先のURLは先のURLと同じで、正しいリンク先になっています。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2018-02-26