たとえば、次のコントローラーがあります
example.com/controller/
次の 3 つの方法があります。
example.com/controller/method1
example.com/controller/method2
example.com/controller/validate
クライアントが有効なCookieを設定しているかどうかを確認するか、ページからそれらを起動するかどうかを確認するコードが含まれているため、検証を確実に実行したいです。
たとえば、次のコントローラーがあります
example.com/controller/
次の 3 つの方法があります。
example.com/controller/method1
example.com/controller/method2
example.com/controller/validate
クライアントが有効なCookieを設定しているかどうかを確認するか、ページからそれらを起動するかどうかを確認するコードが含まれているため、検証を確実に実行したいです。
検証を行うActionFilterが必要だと思います。カスタム検証フィルター属性を作成し、そのOnActionExecutingメソッドをオーバーライドして (Cookie 検証を実行)、属性をコントローラー (または特定のアクション) に適用します。
I would suggest looking at Action filters:
An action filter is an attribute that you can apply to a controller action -- or an entire controller -- that modifies the way in which the action is executed. The ASP.NET MVC framework includes several action filters:
- OutputCache – This action filter caches the output of a controller action for a specified amount of time.
- HandleError – This action filter handles errors raised when a controller action executes.
- Authorize – This action filter enables you to restrict access to a particular user or role.
You also can create your own custom action filters. For example, you might want to create a custom action filter in order to implement a custom authentication system. Or, you might want to create an action filter that modifies the view data returned by a controller action.
このチェックを実行するタイミングに応じて、これをコントローラーのコンストラクターに配置するか、ベース コントローラー (通常は AsyncController) から OnActionExecuting をオーバーライドできます。
このチェックをすべてのコントローラーで実行する場合は、他のコントローラーが継承できるように ControllerBase クラスを作成することをお勧めします。
検証コードをアクションからカスタム認証フィルターに移動する必要があります。アクション フィルターとは異なり、承認フィルターは最初に実行されるフィルターであるため、この種のセキュリティ チェックに使用する必要があります。
まともな仕事をする組み込みの承認フィルターが既にありAuthorize
ます。カスタムのものを作成したい場合は、Authorize
属性を拡張して必要なメソッドをオーバーライドすることをお勧めします。このAuthorize
属性は、キャッシュの問題を回避するためのいくつかの回避策を実行するため、私はそれをお勧めします。