简体   繁体   中英

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?

As far as im 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
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM