ASP.NETで301 リダイレクトを実装するコードを紹介します。
手順
aspxファイルでの実装例です。WebフォームのPage_Loadイベントに下記のコードを実装します。
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.AddHeader("Location", "(リダイレクト先URL)");
例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Redirect301
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.AddHeader("Location", "http://www.ipentec.com");
}
}
}
解説
HttpContext.Current.Response.Status = "301 Moved Permanently";
にて、301のステータスコードを設定します。
HttpContext.Current.Response.AddHeader("Location", "http://www.ipentec.com");
AddHederメソッドを呼び出して、Locationパラメータにリダイレクト先のURLを設定します。上記のコードではhttp://www.ipentec.com へのリダイレクトを設定しています。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2017-10-06