控制器动作命名约定 [英] Controller actions naming convention

查看:93
本文介绍了控制器动作命名约定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如命名约定所述,WebApi控制器动作名称应为Get(),Put(). Post()等.但是请告诉我,如果我有一个控制器为 CustomerController ,现在我想在其中执行两个操作.一个是 GetCustomerById(int id),另一个是 GetCustomerByAge(int age).这两个动作都将一个参数接受为int.

As naming convention says, WebApi controller actions name should be Get(), Put(). Post() etc. But tell me if I have a controller as CustomerController, now I want to have two actions inside of it. One is GetCustomerById(int id) and another one is GetCustomerByAge(int age). Here both the actions accept one parameter as int.

因此,如果我想使url用户友好(如"api/customer/" ),我也想遵循操作命名约定,例如仅 Get(int id)/Get(年龄),我该怎么做?

So, if I want to make the url user friendly like "api/customer/" also I want to follow the actions naming convention like only Get(int id)/Get(int age), how will I do it?

推荐答案

如果您希望Web Api在路由时查找操作名称,请将App_Start文件夹中的WebApiConfig.cs类更改为以下名称:

If you want Web Api to look for the action name when routing, change the WebApiConfig.cs class in the App_Start folder to below:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

然后您可以向GET请求

Then you can just make a GET request to

http://mysite/api/customer/GetCustomerById/1

此外,我建议您研究以下文章以加深了解:

Also I recommend you to study the article below for deeper understanding:

按操作名称进行路由

这篇关于控制器动作命名约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆