Ambiguous invocation of asp.net mvc action methods

Can someone explain why the POST call for the following actions is ambiguous? Do they have different parameters?

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

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

The following is the implementation of what I am using, found in 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; } } 
+4
source share
3 answers

OK, to answer my own question, it was my stupidity!

My get method has a setID parameter, and since it is in the URL, of course it will also be in the message, and therefore RequireRequestValueAttribute returns TRUE for IsValidForRequest for both methods . I walked around it by adding the [HttpGet] attribute to the Get method so things would never be sent to it.

0
source

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

You cannot have two action names with the same name that can be invoked using the same verb (in your case, GET). You need to either rename one of them, or use a different HTTP verb, as with the POST action.


UPDATE:

You can try to enter an HTTP verb into the attribute of a custom action:

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

but honestly, I would not use a special action selector to check for the presence or absence of a query parameter. Route restrictions or data annotations seem much more appropriate for this task.

+6
source

Do yourself a great service. Download the source code for ASP.NET MVC. (In fact, you should do this anytime you have luxurious access to the source code.) Set it to debug and go through the part you come across. I canโ€™t say how many times this has clarified this problem for me. You will get a much better idea of โ€‹โ€‹what is actually happening, what you would otherwise have, and it may be really amazing what you find in some cases. In the past, I asked questions here, received โ€œworkableโ€ solutions, but found that there is a much simpler and more elegant way to solve the problem.

+3
source

Source: https://habr.com/ru/post/1334996/


All Articles