The goal of this tutorial is to explain how to create a new controller action. You will understand the requirements of the Controller method. You will also learn how to prevent a method from being exposed as a controller action.
Add an action to the Controller
By adding a new method to the Controller, you add a new action to the Controller. For example, the Controller in Listing 1 contains an action named Index () and an action named SayHello. Both methods are public as controllers.
Listing 1 -- Controllers \ HomeController. cs
Using System; using System. collections. generic; using System. linq; using System. web; using System. web. mvc; namespace MvcApplication1.Controllers {[HandleError] public class HomeController: Controller {public ActionResult Index () {return View ();} public string SayHello () {return "Hello! ";}}} To expose a method as a controller, it must meet specific requirements:
· This method must be a public method.
· This method cannot be a static method.
· This method cannot be an extension method.
· This method cannot be a constructor, getter, or setter ).
· This method cannot have a public set type.
· This method cannot be a method of the controller base class.
· This method cannot contain reference (ref) or output (out) parameters.
Note that the return type of the controller action is unlimited. A controller action can return an instance of the string type, date and time type, and Random type, or a null value. The ASP. net mvc Framework converts any other type that is not the action result type to the string type and then presents it in the browser.
When you add any method that does not violate these requirements to the Controller, the method will be exposed as a controller action. Be careful here. The Controller method can be requested by anyone accessing the Internet. Therefore, you must not create a controller action such as DeleteMyWebsite.
Prevents a public method from being requested
If you want to create a public method in the Controller class and do not want to expose it as a controller action, you can use the [NonAction] attribute to prevent the method from being requested. For example, the Controller in Listing 2 contains a public method named CompanySecrets () modified by the [NonAction] attribute.
Listing 2 -- Controllers \ WorkController. cs
Using System. web. mvc; namespace MvcApplication1.Controllers {public class WorkController: Controller {[NonAction] public string CompanySecrets () {return "This information is secret. ";}}} if you attempt to request the CompanySecrets () controller action by typing/Work/CompanySecrets in the browser's address bar, you will get the error message shown in Figure 1.
Figure 1: request a NonAction Method
Article Source: Kinglee's Blog (http://www.cnblogs.com/Kinglee)