为何Web API惯例省略{action}?自定义含{action}路由更实用
{action} Great question! Let’s break down why the Web API docs call omitting {action} the conventional approach, even though adding it (like you’ve done) is totally valid and practical.
First, this ties back to Web API’s core design focus on RESTful resource-oriented architecture. REST APIs are built around resources (think products, orders, users) rather than individual methods. The intended action on a resource is conveyed by HTTP verbs (GET, POST, PUT, DELETE) instead of spelling it out in the URL. For example:
GET /api/productsmaps to aGet()action inProductsControllerto fetch all productsPOST /api/productsmaps to aPost(Product model)action to create a new productPUT /api/products/123maps to aPut(int id, Product model)action to update product 123
By omitting {action}, URLs stay clean and centered on the resource itself, which aligns with REST best practices. This is why it’s labeled the "conventional" setup—it’s the default for building modern, standard-compliant web services.
But Your {action} Setup Is Perfectly Reasonable!
Don’t dismiss your approach—adding {action} to your route template ("{controller}/{action}") shines in many scenarios:
- You’re building an RPC-style API (instead of strict REST) where operations don’t fit neatly into CRUD verbs. Think actions like
/api/orders/ProcessRefundor/api/users/SendPasswordResetEmail—spelling these out in the URL makes the API’s intent immediately clear. - Your team prefers explicit routing for easier debugging and testing. Being able to call
http://localhost:1111/controllerName/MethodNamedirectly is incredibly convenient during development, no need to map actions to specific HTTP verbs first.
Web API is flexible enough to support both styles—there’s no universal "right" choice, just different use cases. The docs highlight the omitted {action} as conventional because REST is the dominant paradigm for public APIs, but internal or specialized APIs often benefit from the explicitness of including {action}.
内容的提问来源于stack exchange,提问作者yu yang Jian

