TOC

This article is currently in the process of being translated into Japanese (~1% done).

コントローラー:

アクション

コントローラーは単なる.NETのクラスなので、フィールド、プロパティ、メソッドを持つことができます。特にコントローラーのメソッドは、ブラウザー(つまりユーザー)とアプリケーションを結ぶものとして興味深いものです。そのため、コントローラークラスのメソッドはアクションと呼ばれています。メソッドはアプリケーション内でのアクションに対応すしており、ブラウザー(ユーザー)に何がしかを返すものです。

ブラウザーはURLを呼び出すことで動作するものなので、何らかの方法でURLをそれに対応するコントローラーとアクション(メソッド)に変換する必要があります。たとえばブラウザーが/products/1/というURLをリクエストしたらProductsControllerDetailsメソッド(アクション)に処理させたいとしましょう。これはルーティングという仕組みを用いて実現されるのですが、詳細はこのチュートリアルで別に説明します。今はとりあえず、ルーティングとはURLをコントローラーのアクションに結び付けるものであると理解してください。

コントローラーを作成するときは、コントローラーのpublicメソッドはすべて、アクションとみなされることに注意してください。つまり、コントローラーに対してキャッチオールためのルーティング規則を定義した場合(普通はそうします)、理論的にはURLを使うことでコントローラー内のすべてのメソッドにアクセスできるようになるということです。そのため、エンドユーザーに呼び出してほしくないメソッドがあるなら、privateにしてください。もしどうしてもpublicメソッドにしたいがURLからアクセスされたくない場合は、メソッドに[NonAction]属性を付けるという方法があります。

Action Verbs

To gain more control of how your actions are called, you can decorate them with the so-called Action Verbs. These are in fact regular .NET attributes, which will tell the .NET framework how an action can be accessed. Without these attributes, an action can be accessed using all possible HTTP methods (the most common ones are GET and POST), but you can change that pretty easily:

[HttpGet]
public IActionResult Edit()
{
return Content("Edit");
}

Now the Edit action can only be accessed with a GET request. This has the added benefit of allowing you to have multiple methods with the same name, as long as they don't accept the same request method. So for instance, you could have two methods called Edit: The first one would be available for GET requests and generate the FORM for editing an item, while the second one would only be available for POST requests and be used to update the item when the FORM was posted back to the server. It could look like this:

[HttpGet]
public IActionResult Edit()
{
return View();
}

[HttpPost]
public IActionResult Edit(Product product)
{
product.Save();
return Content("Product updated!");
}

Now whenever a request is made to the Edit() method/action, the actual method responding to the request will be based on whether it's a GET or a POST request.

In some situations, you may want to specify multiple Action Verbs, e.g. to specify that an action can be accessed by both POST and GET requests but not other types. That's just as easy:

[HttpGet]
[HttpPost]      
public IActionResult Edit()
{
...

Summary

We have now learned more about one of the most important aspects of a Controller: The Actions, sometimes referred to as Action Methods or just methods, since that's what they basically are. In the next article we'll discuss the result of these actions, referred to as Action Results.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!