404 - A public action method X was not found on controller Y (ActionInvoker.InvokeAction returns false)

前端 未结 2 2023
故里飘歌
故里飘歌 2021-02-05 00:45

This is NOT a duplicate question, and the problem is driving me crazy. I am getting the typical error \"A public action method X was not found on controller Y\" which returns a

2条回答
  •  爱一瞬间的悲伤
    2021-02-05 01:11

    The problem is that you're specifying both the HttpGet and HttpPost attributes. If you leave both of them off, the action accepts both POST and GET requests. My guess is that the HttpGet and HttpPost attributes don't signal to MVC to allow the corresponding request type, but to deny the opposite type. So by including [HttpPost], you're denying GET requests, and by including [HttpGet], you're denying POST requests...effectively denying all request types. Leave the attributes off and it will accept both types.

    Update: I just checked the MVC source, and my assumption is correct. In ActionMethodSelector, it checks the attributes thusly:

    if (attrs.All(attr => attr.IsValidForRequest(controllerContext, methodInfo))) {
        matchesWithSelectionAttributes.Add(methodInfo);
    }
    

    In other words, all ActionMethodSelectorAttribute (from which HttpPostAttribute and HttpGetAttribute derive) must return true for the action to be invoked. One or the other is always going to return false, so the action will never execute.

提交回复
热议问题