Non Action Selector in MVC

Non Action Selector in ASP.NET MVC

In this article, I am going to discuss Non Action Selector in MVC. Please read Action Name and Action Verb article before proceeding to this article as we are going to use the same example that we worked on in our previous two articles.

An action method is a public method in a controller that can be invoked using a URL. So, by default, if we have any public method in a controller then it can be invoked using a URL request.

To restrict access to public methods in a controller Non Action attribute can be used. Non Action is another built-in attribute, which indicates that a public method of a Controller is not an action method. It is used when we want that method shouldn’t be treated as an action method.

Let’s understand this with an example.
public class HomeController : Controller
{
    [HttpGet]
    public string Method1()
    {
        return "<h1>Method 1 Invoked</h1>";
    }

    [HttpGet]
    public string Method2()
    {
        return "<h1>Method 2 Invoked</h1>";
    }
}
We have 2 public methods in HomeController, Method1() and Method2().

Method1 can be invoked using URL /Home/Method1

Method2 can be invoked using URL /Home/Method2

Let’s say Method2() is for doing some internal work, and we don’t want it to be invoked using a URL request. To achieve this, decorate Method2() with NonAction attribute as shown below.

[NonAction]
public string Method2()
{
    return "<h1>Method 2 Invoked</h1>";
}

Now, if we navigate to URL /Home/Method2, we will get an error – The resource cannot be found. As shown below.

Non Action Selector in ASP.NET MVC

Another way to restrict access to methods in a controller is by making them private. 
private string Method2()
{
    return "<h1>Method 2 Invoked</h1>";
}

In general, it’s a bad design to have a public method in a controller that is not an action method. If we have any such method for performing business calculations, it should be somewhere in the model and not in the controller.

However, if for some reason, if we want to have public methods in a controller and we don’t want to treat them as actions, then use Non Action attribute. 

SUMMARY

In this article, I try to explain Non Action Selector in ASP.NET MVC application step by step with a real time example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *