方法名称中的隐式动词
Implicit Verbs from Method name
如果我创建一个网络Api controller
,并使用以 http 动词为前缀的方法填充它,Api 能够正确地暗示应该在该控制器上使用什么动词.
public class TestController : ApiController
{
public string GetData()
{
return "Called Get Method";
}
public string PostData()
{
return "Called Post Method";
}
public string PutData()
{
return "Called Put Method";
}
}
如果我将 Post
替换为 Update
,Post 方法将继续隐式工作。
public string UpdateData()
{
return "Called Updated Method";
}
是否有一个方法的可能前缀列表以及它们映射到的动词?另外,是否可以定义自定义前缀?例如,如果我想始终将以 "Search" 开头的方法映射到 Post
,我可以定义这个吗?
如果您 Routing
像下面这样:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
考虑 routeTemplate
。您现在可以按名称调用 controller
上的 action
,并且不应该存在 prefix
问题。如果您在 controller
上有多个类似 HTTP Verbs
的操作(多个 GET
或 POST
说),这种方法非常有用。
隐式动词是内置路由的功能,似乎无法手动扩展。
此 Asp.Net 详细介绍了隐式路由的具体规则。
HTTP Methods. The framework only chooses actions that match the HTTP method of the request, determined as follows:
- You can specify the HTTP method with an attribute: AcceptVerbs, HttpDelete, HttpGet, HttpHead, HttpOptions, HttpPatch, HttpPost, or HttpPut.
- Otherwise, if the name of the controller method starts with "Get", "Post", "Put", "Delete", "Head", "Options", or "Patch", then by convention the action supports that HTTP method.
- If none of the above, the method supports POST.
UpdateData
方法之所以有效,是因为任何未隐式确定的方法都会自动成为 Post
如果我创建一个网络Api controller
,并使用以 http 动词为前缀的方法填充它,Api 能够正确地暗示应该在该控制器上使用什么动词.
public class TestController : ApiController
{
public string GetData()
{
return "Called Get Method";
}
public string PostData()
{
return "Called Post Method";
}
public string PutData()
{
return "Called Put Method";
}
}
如果我将 Post
替换为 Update
,Post 方法将继续隐式工作。
public string UpdateData()
{
return "Called Updated Method";
}
是否有一个方法的可能前缀列表以及它们映射到的动词?另外,是否可以定义自定义前缀?例如,如果我想始终将以 "Search" 开头的方法映射到 Post
,我可以定义这个吗?
如果您 Routing
像下面这样:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
考虑 routeTemplate
。您现在可以按名称调用 controller
上的 action
,并且不应该存在 prefix
问题。如果您在 controller
上有多个类似 HTTP Verbs
的操作(多个 GET
或 POST
说),这种方法非常有用。
隐式动词是内置路由的功能,似乎无法手动扩展。
此 Asp.Net 详细介绍了隐式路由的具体规则。
HTTP Methods. The framework only chooses actions that match the HTTP method of the request, determined as follows:
- You can specify the HTTP method with an attribute: AcceptVerbs, HttpDelete, HttpGet, HttpHead, HttpOptions, HttpPatch, HttpPost, or HttpPut.
- Otherwise, if the name of the controller method starts with "Get", "Post", "Put", "Delete", "Head", "Options", or "Patch", then by convention the action supports that HTTP method.
- If none of the above, the method supports POST.
UpdateData
方法之所以有效,是因为任何未隐式确定的方法都会自动成为 Post