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开发者_C百科.HttpContext.Request[ValueName] != null);
}
public string ValueName { get; private set; }
}
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.
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.
OK to answer my own question, it was my stupidity!
My get method has the setID parameter and because it is in the URL, of course this will also be in the post, and therefore RequireRequestValueAttribute was returning TRUE for IsValidForRequest for both methods. I got around it by adding a [HttpGet] attribute to the Get method so things will never get posted to it.
精彩评论