[Boiled ASP. NET Web API2 methodology] (3-7) default Action request method and NonActionAttribute,
Problem
There is a public method in the Controller, but you do not want to expose this publlic method as an API.
Solution
In ASP. NET Web APIs, HTTP predicates are normally used to match related actions in the Controller. By default, every public method in Contoller is an Action. To prevent the public method from becoming an Action, you only need to use the [NonAction] attribute on the public method.
Working Principle
NoActionAttribute (as shown in code snippet 3-19) is a non-operation class, with nothing to do, but a tag.
Code snippet 3-19. NonAction Definition
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]public sealed class NonActionAttribute : Attribute{}
ApiControllerActionSeletor: When the Controller finds an appropriate Action, internal verification is executed, as shown in code snippet 3-10. It uses all public methods in the Controller as potential actions, then perform the filtering step by step. The declaration and ApiController will be excluded, and the Declaration and IHttpController will also be excluded. Finally, if NonActionAttribute is used, the declaration will be excluded.
Code snippet 3-20 ApiControllerActionSelector: Action Filtering Rule
Note:The verification logic is inApiControllerAtionSelectorInternal, if your code inherits and implementsIHttpActionSelectorTo ensure that your implementations have code similar to the logicNonActionAttributeWorking properly.
In the ReflectHttpActionDescriptor class, ASP. net web api encapsulates every Action. In addition, it is also responsible for identifying the request type that Action should process Http. It uses the method name or related attributes (HttpGetAttribute, HttpPostAttribute, and so on ). If the Action name starts with an HTTP verb (GET, POST, PUT, DELETE), ASP. net web api also considers this Action suitable for processing HTTP requests.
In addition, if the Action method does not have any prefix or declaration attribute, ASP. net web api can only process POST requests by default. This is a very red and easy to be ignored. Many beginners will think that there is no prefix or attribute Declaration, so the client cannot request this Action.
Code demo
Code snippet 3-21 shows three Action methods.
Code snippet 3-21. NonActionAttribute example