Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ambiguous call asp.net mvc action methods

Can someone explain why POST call to the following actions is ambiguous? They have different set of parameters?

[RequireRequestValueAttribute("setID")]
public ActionResult Add(int setID){}

[HttpPost]
public ActionResult Add(TypeModel model, int? queueID) {}

The issue only occurs when using the RequireRequestValueAttribute attribute, which I am using because I wanted to add another method for a Get call with different set of parameters.

Following is the implementation of that that I am using, found on another stackoverflow question:

public class RequireRequestValueAttribute : ActionMethodSelectorAttribute
{
    public RequireRequestValueAttribute(string valueName)
    {
        ValueName = valueName;
    }
    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
    {
        return (controllerContext.HttpContext.Request[ValueName] != null);
    }
    public string ValueName { get; private set; }
} 
like image 455
lahsrah Avatar asked Jan 20 '23 18:01

lahsrah


2 Answers

It's because in C# it is forbidden to have two methods with the same name and parameter types. This has nothing to do with ASP.NET MVC. You should rename one of the two Add actions that could be invoked by GET.

You cannot have two action names with the same name which can be invoked with the same verb (in your case GET). You need to either rename one of them or use another HTTP verb as you did with your POST action.


UPDATE:

You could try introducing the HTTP verb in the custom action selector attribute:

public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{
    return controllerContext.HttpContext.Request[ValueName] != null &&
           controllerContext.HttpContext.Request.HttpMethod == "GET";
}

but quite frankly I wouldn't use a custom action selector to validate whether are request parameter is present or not. Route constraints or data annotations seem far more appropriate for this task.

like image 102
Darin Dimitrov Avatar answered Jan 28 '23 19:01

Darin Dimitrov


Do yourself a huge favor. Download the source for ASP.NET MVC. (Actually, you should do this anytime you have the luxury accessing the source code.) Set it up to debug and step through the part you are having trouble with. I cannot tell you how many times this has cleared up a problem like this for me. You will get a much better understanding of what is actually going on that you would otherwise have, and it can be really surprising what you find in some cases. I have in the past asked questions here, gotten 'workable' solutions, only to discover that there was a much easier, more elegant way of resolving the problem.

like image 36
Paul Avatar answered Jan 28 '23 19:01

Paul