9

I have a method in my controller that I don't want to be called from the address bar in the browser...

Is there a way to do that? Maybe some kind of annotation, modification in the route configuration? Which are my options?

amp
  • 11,754
  • 18
  • 77
  • 133
  • How would you prefer this `Action` to be called? `HttpPost` only? Or are you going to call it from within the `Controller`? Could it just be a regular method instead of an `Action`? I think the only way you're going to be able to do this is by using the `[HttpPost]` attribute. – Rohrbs May 22 '13 at 17:30

2 Answers2

16

If you are going to use this action only from within your controller or Views then you can use ChildActionOnly attribute.

If you want to access it using POST then you can use [HttpPost] attribute.

But if you wish to use it using GET (i.e. using AJAX call etc) and don't want users to access it using address bar then you can follow this tutorial to make your actions AJAX only.

Or, if you simply want a method that is not an Action at all (i.e. cannot be called using HTTP) then you can either make it private or use [NonAction] attribute

U.P
  • 7,357
  • 7
  • 39
  • 61
  • I would like to add the ChildActionOnly will only work from Views. If tried to call them from Controller, you will face error as *The action 'Authenticate' is accessible only by a child request.* – Vikram Singh Saini Jan 16 '16 at 15:23
8

Use NonAction attribute on the method.

Herman Kan
  • 2,253
  • 1
  • 25
  • 32
  • 1
    Can you explain this attribute please ? – Zulu May 25 '15 at 17:45
  • @Zulu, the attribute is to be applied to the controller method which you want to make unavailable as an action: see https://msdn.microsoft.com/en-us/library/system.web.mvc.nonactionattribute.aspx. – Herman Kan May 26 '15 at 05:14