アプリケーションのルートのURLパスを取得する (仮想アプリケーションのルートパスの取得)

ASP.NETアプリケーションをサーバールート以外の場所に設置した場合、設置場所のURLパスを取得したいことがあります。

http://app.ipentec.com/webapp/photoeditor/default.aspx
がWebアプリのトップページとした場合、 ページ間リンク等を動的に生成する場合、/webapp/photoeditor 部分が知りたいことがあります。

アプリケーションのルートのURLパス(仮想アプリケーションのルートパス)の取得は Request.ApplicationPathを使うと取得できます。

コード例

Webフォームにliteralコントロールを1つ配置します。Webフォームに以下のコードを記述します。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebAppPathDemo
{
  public partial class WebForm : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      Literal1.Text = "";
      Literal1.Text += string.Format("Request.ApplicationPath: {0:s}<br/>",
        Request.ApplicationPath);
    }
  }
}

実行結果

アプリケーションを http://app.ipentec.com/webapp/photoeditor/ に設置した場合、http://app.ipentec.com/webapp/photoeditor/WebForm.aspxにアクセスすると

Request.ApplicationPath: /webapp/photoeditor

がページに表示されます。

AuthorPortraitAlt
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
作成日: 2011-10-20
Copyright © 1995–2025 iPentec all rights reserverd.