RedirectResult クラス (System.Web.Mvc)

提供: MonoBook
2012年7月11日 (水) 10:35時点におけるimported>Administratorによる版 (→‎301リダイレクト)
(差分) ← 古い版 | 最新版 (差分) | 新しい版 → (差分)
ナビゲーションに移動 検索に移動

RedirectResultクラスとは、ASP.NET MVCアクション・メソッドの戻り値(ActionResultクラスおよびその派生クラス)として、Webブラウザに対して指定されたURIリダイレクトするよう指示するHTTPレスポンスヘッダーを生成、送信するクラスである。

使い方[編集 | ソースを編集]

RedirectResultクラスの使い方はいたって簡単。 単純にリダイレクト先のURLを指定するだけである。 これでWebブラウザに対して302リダイレクトを送信する。

using System.Web.Mvc;

public class HomeController : Controller 
{
    public ActionResult Index() 
    {
        return new RedirectResult( "http://monobook.org/wiki/PHP" );
    }
}

これはPHPでいう以下のコードに相当する。

<?php
header( "Location: http://monobook.org/wiki/PHP" );

301リダイレクト[編集 | ソースを編集]

ASP.NET MVC 3では、bool型のPermanentというプロパティが追加され、永続的に移転したことを示す永久リダイレクト(301リダイレクト)を発生させるかを指定できるようになった。Permanentプロパティの値はRedirectResultクラスのコンストラクタの2番目の引数として指定することもできる。

なお、ASP.NET MVC 3で追加されたものでありASP.NET MVC 2以前では存在しないので注意。

using System.Web.Mvc;

public class HomeController : Controller 
{
    public ActionResult Index() 
    {
        // ASP.NET MVC 3でコンストラクタに第2引数(bool型)が追加され、
        // trueにすると301リダイレクトになる。
        return new RedirectResult( "http://monobook.org/wiki/PHP", true );
    }
}

これはPHPでいう以下のコードに相当する。

<?php
header( "HTTP/1.1 301 Moved Permanently" ); 
header( "Location: http://monobook.org/wiki/PHP" );

ASP.NET MVC 2以前で301リダイレクトをしたい場合はActionResultクラス継承した自前クラスを作る。

using System.Web.Mvc;

public class PermanentRedirectResult : ActionResult
{
    public string Url { get; set; }

    public PermanentRedirectResult(string url)
    {
        this.Url = url;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        if (string.IsNullOrEmpty(this.Url))
        {
            throw new ArgumentException("url is null or empty", "Url");
        }

        context.HttpContext.Response.StatusCode = 301;
        context.HttpContext.Response.RedirectLocation = this.Url;
        context.HttpContext.Response.End();
    }
}

関連項目[編集 | ソースを編集]

参考文献[編集 | ソースを編集]


外部リンク[編集 | ソースを編集]