Non-Action Selector in ASP.NET MVC

Non-Action Selector in ASP.NET MVC Application

In this article, I am going to discuss the Non-Action Selector in ASP.NET MVC Application with examples. Please read our previous article before proceeding to this article as we are going to work the same example that we worked on in our previous two articles. In our previous article, we discussed the Action Verb Action Selector in ASP.NET MVC Application with examples.

Why do we need Non-Action Selector in ASP.NET MVC?

By default, in ASP.NET MVC, an action method is a public method in a controller that can be invoked using a URL request. But in some scenarios, we need to restrict the public methods of a controller to be invoked by a URL.

To restrict access to the public methods in a controller, we need to decorate the action method with the Non-Action attribute. The Non-Action is another built-in Action Selector 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.

Understanding Non-Action Attribute 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>";
    }
}

As you can see in the above code, we have 2 public methods i.e. Method1() and Method2() in HomeController. 

Method1 can be invoked using URL /Home/Method1
Method2 can be invoked using URL /Home/Method2

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

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

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

Non-Action Selector in ASP.NET MVC Application

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 you want to have public methods in a controller and you don’t want to treat them as actions, then use the Non-Action attribute. 

In this article, I try to explain the 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 *