ASP .NET MVCでの画像出力

テクノロジー: .NET Framework 3.5、ASP .NET MVC

言語: Visual Basic .NET、C#



多くの場合、Webアプリケーションを開発するときは、html以外の形式でユーザーデータを提供する必要があります。 たとえば、画像の小さなコピー(ThumbImage)を表示するか、データベースから保護されたデータを返します。 ASP .NET WebFormsでは、これらの目的でハンドラーまたは通常のASPXページを使用できます。 ASP .NET MVCでは、状況は少し変わりました。 もちろん、以前と同様に、ハンドラーを使用することは禁止されていません。 場合を除き、Routing.IgnoreRoute( "{resource} .ashx")などのルーティングのルールが必要になる場合があります。

このレビューでは、ASP .NET MVCツールを使用した画像出力の例を検討しますが、説明したアプローチを使用して、あらゆる形式のデータを出力できます。





アクション結果





ご存知のとおり(既知であることを願っています)、コントローラー(コントローラー)のアクション(アクション)の実行結果はActionResultです。 ActionResultは、すべてのクラスが継承する基本クラスであり、最終的にクライアントへの出力用のコンテンツを生成します。 例:ViewResult、JsonResult、ContentResult、RedirectResultなど。 ActionResultクラスは単独では使用できず、継承することしかできません。これにより、コントローラーアクションの結果のリストは開発者の想像力によってのみ制限されます。

出力用のデータは、 ExecuteResultメソッドで生成されます。



画像結果





実際には、コントローラーがクライアントにイメージを提供できるように、ActionResultから継承したクラスを記述する必要があります。 論理的には、彼の名前はImageResultでなければなりませんが、それはあなた次第です。



VB .NET:

Public Class ImageResult

Inherits ActionResult

End Class








C#:

public class ImageResult: ActionResult

{ }









前述したように、コンテンツはExecuteResultメソッドで生成されますが、これを行う前に、ソースマテリアルを取得する必要があります。 言い換えると、最終データの生成に基づいてクラスに情報を渡します。 画像の場合、ほとんどの場合、Streamクラスに渡されます。 また、コンテンツの種類(Content-Type)に関する情報を送信して、検索エンジンが恐れないようにし、ブラウザがコーヒーを推測しないようにし、その結果、ユーザーの精神を傷つけないようにする必要があります。 これを行うには、関連するプロパティをいくつか記述し、図を完成させるためにコンストラクターを登録する必要があります。



VB .NET:

Private _ImageStream As Stream

Private _ContentType As String = ""



Public Property ImageStream() As Stream

Get

Return _ImageStream

End Get

Set ( ByVal value As Stream)

_ImageStream = value

End Set

End Property



Public Property ContentType() As String

Get

Return _ContentType

End Get

Set ( ByVal value As String )

_ContentType = value

End Set

End Property



Public Sub New( ByVal imageStream As Stream, ByVal contentType As String )

If imageStream Is Nothing Then Throw New ArgumentNullException("imageStream")

If String .IsNullOrEmpty(contentType) Then Throw New ArgumentNullException("contentType")

_ImageStream = imageStream

_ContentType = contentType

End Sub








C#:

private static Stream _ImageStream;

private static string _ContentType = "";



public static Stream ImageStream

{

get { return _ImageStream; }

set { _ImageStream = value; }

}



public static string ContentType

{

get { return _ContentType; }

set { _ContentType = value; }

}



public ImageResult(Stream imageStream, string contentType)

{

if (imageStream == null) throw new ArgumentNullException("imageStream");

if ( String .IsNullOrEmpty(contentType)) throw new ArgumentNullException("contentType");

_ImageStream = imageStream;

_ContentType = contentType;

}








これを終了するには、ExecuteResultメソッドのコードを記述する必要があります。このコードでは、受信したデータに基づいて画像が表示されます。



VB .NET:

Public Overrides Sub ExecuteResult( ByVal context As System.Web.Mvc.ControllerContext)

If context Is Nothing Then Throw New ArgumentNullException("context")

Dim Response As HttpResponseBase = context.HttpContext.Response

Response.ContentType = _ContentType

Dim buffer(1024) As Byte

Do

Dim read As Integer = _ImageStream.Read(buffer, 0, buffer.Length)

If read = 0 Then Exit Do

Response.OutputStream.Write(buffer, 0, read)

Loop

Response.End()

End Sub








C#:

public static override void ExecuteResult(System.Web.Mvc.ControllerContext context)

{

if (context == null) throw new ArgumentNullException("context");

HttpResponseBase Response = context.HttpContext().Response;

Response.ContentType = _ContentType;

byte [] buffer = new byte [1024];

do

{

int read = _ImageStream.Read(buffer, 0, buffer.Length);

if (read == 0) { break ; }

Response.OutputStream.Write(buffer, 0, read);

} while ( true );

Response.End();

}








これで、任意のコントローラーのアクションの結果がImageResultになります。



VB .NET:

Return New ImageResult(System.IO.File.OpenRead("C:\kbyte.ru.gif"), "image/gif")







C#:

return new ImageResult(System.IO.File.OpenRead("C:\\kbyte.ru.gif"), "image/gif");







延長





完全に幸せにするために、System.Web.Mvc.Controllerの拡張機能を作成できます。 これを行うには、ユーザーは通常のモジュール(Module)を作成し、たとえばControllerExtensionsなどの名前で静的クラスをsishnikiし、ImageResultが返す便利な関数を書き込みます。



ご注意 System.Runtime.CompilerServices名前空間をインポートすることを忘れないでください。



VB .NET:

Public Module ControllerExtensions



<Extension()> _

Public Function Image( ByVal controller As System.Web.Mvc.Controller, ByVal imageStream As Stream, ByVal contentType As String ) As ImageResult

Return New ImageResult(imageStream, contentType)

End Function



<Extension()> _

Public Function Image( ByVal controller As System.Web.Mvc.Controller, ByVal imageBytes() As Byte , ByVal contentType As String ) As ImageResult

Return New ImageResult( New MemoryStream(imageBytes), contentType)

End Function



<Extension()> _

Public Function Image( ByVal controller As System.Web.Mvc.Controller, ByVal fileName As String , ByVal contentType As String ) As ImageResult

Return New ImageResult(System.IO.File.OpenRead("C:\kbyte.ru.gif"), contentType)

End Function



End Module








C#:

public static class ControllerExtensions

{



[Extension()]

public static ImageResult Image(System.Web.Mvc.Controller controller, Stream imageStream, string contentType)

{

return new ImageResult(imageStream, contentType);

}



[Extension()]

public static ImageResult Image(System.Web.Mvc.Controller controller, byte [] imageBytes, string contentType)

{

return new ImageResult( new MemoryStream(imageBytes), contentType);

}



[Extension()]

public static ImageResult Image(System.Web.Mvc.Controller controller, string fileName, string contentType)

{

return new ImageResult(System.IO.File.OpenRead("C:\\kbyte.ru.gif"), contentType);

}



}








これで、コントローラーで所定の機能を使用できます。次に例を示します。



VB .NET:

Return Image(System.IO.File.OpenRead("C:\kbyte.ru.gif"), "image/gif")







C#:

return Image(System.IO.File.OpenRead("C:\\kbyte.ru.gif"), "image/gif");







あとがき





ActionResultクラスから継承すると、絶対にあらゆる形式のデータを表示できます。 ExecuteResultメソッドに登録されるコードの機能は、想像力に完全に依存します。 画像については、ファイルから画像を出力する場合は、将来的に(ファイル上で)操作する必要がある場合に誤ってファイルをロックしないように、最初にそれらを読み取ることをお勧めします(たとえば、バイト配列でコピーを作成する) (移動、削除)。



-

ネミロ・アレクセイ

06/29/2009



All Articles