ASP.Net Web API custom action taking multiple argu

2019-06-11 13:55发布

I want to implement a custom action in a Web API controller that takes multiple arguments with ASP.Net MVC 4 Web API framework.

 public class APIRepositoryController : ApiController
{
    ...
    [HttpGet, ActionName("retrieveObservationInfo")]
    public ObservationInfo retrieveObservationInfo(
                    int id, 
                    String name1, 
                    String name2)
    {
        //...do something...
        return ObservationInfo;
    }
    ...
}

Such that I can call a URL in the web browser like:

"http://[myserver]/mysite/api/APIRepository/retrieveObservationInfo?id=xxx&name1=xxx&name2=xxx"

However, this has never worked.

Is there anything else I need to configure, e.g. WebAPI routing? Currently I just use the default WebApiConfig.cs.

Thanks in advance

1条回答
走好不送
2楼-- · 2019-06-11 14:16

By default Web API will dispatch actions based on HTTP verb rather than action name, in your case:

GET http://[myserver]/mysite/api/APIRepository/?id=xxx&name1=xxx&name2=xxx

To dispatch based on action name (like you want), you need to add the following route before the default route:

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

Note that you currently cannot (at least not without hacks) combine verb-based and action-name routing in a single controller reliably. You can read more about Web API routing here.

查看更多
登录 后发表回答