What is Nonaction attribute in ASP.NET MVC

Forums ASP.NET MVCWhat is Nonaction attribute in ASP.NET MVC
Staff asked 3 years ago

Answers (1)

Add Answer
monika gabani Marked As Accepted
Staff answered 3 years ago

The NonAction attribute is used when we want a public method in a controller but do not want to treat it as an action method.

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, NonAction attribute can be used.

Example

Let’s say Method2 in below is for some internal purpose, and we don’t want it to be invoked using a URL request. To achieve this, we have to decorate it with NonAction attribute.

using System.Web.Mvc;
namespace DemoMvcApplication.Controllers{
   public class HomeController : Controller{
      public string Method1(){
         return "<h1>Method 1 Invoked</h1>";
      }
      [NonAction]
      public string Method2(){
         return "<h1>Method 2 Invoked</h1>";
      }
   }
}


Here,Method2 is not accessible with Url because it has nonAction attribute.

Subscribe

Select Categories