- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the significance of NonActionAttribute in ASP .Net MVC C#?
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.
Now let us consider HomeController having two public methods MyMethod1 and MyMethod2.
Controller
Example
using System.Web.Mvc; namespace DemoMvcApplication.Controllers{ public class HomeController : Controller{ public string MyMethod1(){ return "<h1>My Method 1 Invoked</h1>"; } public string MyMethod2(){ return "<h1>My Method 2 Invoked</h1>"; } } }
Let us invoke both the methods in the HomeController using the below URLs.
http://localhost:59146/Home/MyMethod1
http://localhost:59146/Home/MyMethod2
Let's say MyMethod2 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.
Controller
Example
using System.Web.Mvc; namespace DemoMvcApplication.Controllers{ public class HomeController : Controller{ public string MyMethod1(){ return "<h1>My Method 1 Invoked</h1>"; } [NonAction] public string MyMethod2(){ return "<h1>My Method 2 Invoked</h1>"; } } }
Below is the output of making a MyMethod2 Non Action.