I would like to have 4 actions with the same name (controller methods may have a different name, but their ActionName() attribute is the same for all 4 of them:
[ActionName("Same-name")]
public ActionResult AnonAction() { ... }
[HttpPost]
[ActionName("Same-name")]
public ActionResult AnonAction(ModelData data) { ... }
[Authorize]
[ActionName("Same-name")]
public ActionResult AuthAction() { ... }
[HttpPost]
[Authorize]
[ActionName("Same-name")]
public ActionResult AuthAction(OtherData data) { ... }
The first couple does something when users are not authenticated (anonymous users). The second couple does something similar (but not the same) when users are authenticated.
First three action methods work as expected, but I can’t seem to make the last one work. It throws an exception telling me, that it can’t distinguish between POST actions. I don’t think I’ve made anything wrong here or forgotten to do something. I just hope it’s nto a bug in Asp.net MVC 2 RC2.
Does anyone see any flaw in my actions?
@Paco is right.
AuthorizeAttributedoesn’t have anything to do with action selection. His suggestion didn’t feel right so thanks to him I did some digging into MVC code and I came up with the most appropriate solution myself.Solution as it was meant to be
There’s an extensibility point for these things in MVC. Basically what you have to do is to write you own
ActionMethodSelectionAttributethat will handle this. I created one that selects action based on user authorization (either anonymous or authorized). Here’s the code:Additional observation
When I decorated my action methods with my custom attribute I still got the same exception until I added
[HttpGet]to my GET actions. Why is that? I found the answer in the flowchart in Pro ASP.NET MVC Framework book (check it out yourself). Exception was thrown because there were more than just one action method withActionMethodSelectorAttribute. Normally we just decorate out POST actions, but in this case all of them were decorated. 2 for anonymous and 2 for authenticated users. That’s why you have to use bothHttpGetandHttpPoston action methods when you add more selector attributes to them.My controller actions now look like this