Don G
Don G

Reputation: 33

How to override an action in mvc controller?

How to override an action method in a controller? Can anyone explain with a small example. And one more thing to ask , can we do this without virtual keyword?

Upvotes: 0

Views: 10732

Answers (2)

Walter Verhoeven
Walter Verhoeven

Reputation: 4431

You can do this the same as how the Filters will hook into it when you use filters in an mvc solution

public override void OnActionExecuting(ActionExecutingContext context)
{
   if (Request.Headers.TryGetValue("api-key", out var value))
   {
      ///
   }
   base.OnActionExecuting(context);
}

Upvotes: 0

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18883

As far as i m understanding your question these are the answers :

First Answer :

it's not possible to have two controller actions with the same name but with a different result also:

For example:

ActionResult YourAction() { ... }
FileContentResult YourAction() { ... }

In MVC you can also do this :

[HttpGet]
[ActionName("AnyAction")]
ActionResult YourAction(firstModel model1) { ... }

[HttpPost]
[ActionName("AnyAction")]
FileContentResult YourAction(secondModel model1) { ... }

The main idea here is that you can use the ActionNameAttribute to name several action methods with the same name.

----------------------------------------------------------------OR--------------------------------------------------------------

Second Answer :

[NonAction]
public override ActionResult YourAction(FormCollection form)
{
  // do nothing or throw exception
}

[HttpPost]
public ActionResult YourAction(FormCollection form)
{
  // your implementation
}

Upvotes: 1

Related Questions