Sunday, 23 December 2018

Use of NonAction attribute in MVC

An action method is always a public method in a controller that can be invoked using a URL. To restrict access to public methods in a controller, NonAction attribute can be used.

Example:

public class HomeController Controller
{
    public string Index1()
    {
        return "This will respond to URL Request";
    }

    [NonAction]
    public string Index2()
    {
        return "This will not respond URL Request";
    }
}

Index1 method will respond to /home/index1 URL where as Index2 method will not respond to /home/index2 URL request as it is decorated with [NonAction] attribute. If you navigate to URL /Home/Method2, you will get an error - The resource cannot be found.

No comments:

Post a Comment