问题描述
我开始使用 MVC4 Web API 项目,我有多个 HttpPost
方法的控制器.控制器如下所示:
I am starting to use MVC4 Web API project, I have controller with multiple HttpPost
methods. The Controller looks like the following:
控制器
public class VTRoutingController : ApiController
{
[HttpPost]
public MyResult Route(MyRequestTemplate routingRequestTemplate)
{
return null;
}
[HttpPost]
public MyResult TSPRoute(MyRequestTemplate routingRequestTemplate)
{
return null;
}
}
这里的MyRequestTemplate
表示负责处理传入请求的Json的模板类.
Here MyRequestTemplate
represents the template class responsible for handling the Json coming through the request.
错误:
当我使用 Fiddler 为 http://localhost:52370/api/VTRouting/TSPRoute
或 http://localhost:52370/api/VTRouting/Route
发出请求时代码> 我收到一个错误:
When I make a request using Fiddler for http://localhost:52370/api/VTRouting/TSPRoute
or http://localhost:52370/api/VTRouting/Route
I get an error:
找到多个与请求匹配的操作
如果我删除上述方法之一,它就可以正常工作.
If I remove one of the above method it works fine.
Global.asax
我已尝试修改global.asax
中的默认路由表,但仍然出现错误,我认为我在global.asax 中定义路由时遇到问题.这是我在 global.asax 中所做的.
I have tried modifying the default routing table in global.asax
, but I am still getting the error, I think I have problem in defining routes in global.asax. Here is what I am doing in global.asax.
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapHttpRoute(
name: "MyTSPRoute",
routeTemplate: "api/VTRouting/TSPRoute",
defaults: new { }
);
routes.MapHttpRoute(
name: "MyRoute",
routeTemplate: "api/VTRouting/Route",
defaults: new { action="Route" }
);
}
我正在使用 POST 在 Fiddler 中发出请求,在 RequestBody 中为 MyRequestTemplate 传递 json.
I am making the request in Fiddler using POST, passing json in RequestBody for MyRequestTemplate.
推荐答案
您可以在一个控制器中拥有多个操作.
You can have multiple actions in a single controller.
为此,您必须做以下两件事.
For that you have to do the following two things.
首先用
ActionName
属性修饰动作,如
[ActionName("route")]
public class VTRoutingController : ApiController
{
[ActionName("route")]
public MyResult PostRoute(MyRequestTemplate routingRequestTemplate)
{
return null;
}
[ActionName("tspRoute")]
public MyResult PostTSPRoute(MyRequestTemplate routingRequestTemplate)
{
return null;
}
}
第二个在WebApiConfig
文件中定义如下路由.
// Controller Only
// To handle routes like `/api/VTRouting`
config.Routes.MapHttpRoute(
name: "ControllerOnly",
routeTemplate: "api/{controller}"
);
// Controller with ID
// To handle routes like `/api/VTRouting/1`
config.Routes.MapHttpRoute(
name: "ControllerAndId",
routeTemplate: "api/{controller}/{id}",
defaults: null,
constraints: new { id = @"^d+$" } // Only integers
);
// Controllers with Actions
// To handle routes like `/api/VTRouting/route`
config.Routes.MapHttpRoute(
name: "ControllerAndAction",
routeTemplate: "api/{controller}/{action}"
);
这篇关于Web API 控制器中的多个 HttpPost 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!