Api 控制器声明多个 Get 语句 [英] Api controller declaring more than one Get statement

查看:26
本文介绍了Api 控制器声明多个 Get 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 MVC4 中使用新的 Api 控制器,我发现了一个问题.如果我有以下方法:

Using the new Api Controller in MVC4, and I've found a problem. If I have the following methods:

public IEnumberableGetAll()

public IEnumberableGetSpecific(int i)

这会奏效.但是,如果我想检索一些不同类型的不同数据,它默认为 GetAll 方法,即使 $.getJSON 设置为 GetAllIntegers 方法:

This will work. However, if I want to retrieve some different data of a different type, it defaults to the GetAll method, even though the $.getJSON is set to the GetAllIntegers method:

public IEnumberableGetAllIntergers()

(糟糕的命名约定)

我能做到这一点吗?

我可以在 Web API 控制器中只有一个 GetAll 方法吗?

Can I only have a single GetAll method in the Web API controller?

我认为将我想要实现的目标形象化更容易.这是一段代码,用于显示我希望能够在单个 ApiController 中执行的操作:

I think it's easier to visualise what I'm trying to achieve. Here is a snippet of code to show what I'd like to be able to do, in a single ApiController:

public IEnumerable<string> GetClients()
{ // Get data
}

public IEnumerable<string> GetClient(int id)
{ // Get data
}

public IEnumerable<string> GetStaffMember(int id)
{ // Get data
}

public IEnumerable<string> GetStaffMembers()
{ // Get data
}

推荐答案

这一切都在路由中.默认的 Web API 路由如下所示:

This is all in the routing. The default Web API route looks like this:

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

使用默认路由模板,Web API 使用 HTTP 方法来选择操作.结果,它将不带参数的 GET 请求映射到它可以找到的第一个 GetAll.要解决此问题,您需要定义一个包含操作名称的路由:

With the default routing template, Web API uses the HTTP method to select the action. In result it will map a GET request with no parameters to first GetAll it can find. To work around this you need to define a route where the action name is included:

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

之后,您可以使用以下 URL 为请求加星标:

After that you can star making requests with following URL's:

  • api/yourapicontroller/GetClients
  • api/yourapicontroller/GetStaffMembers

这样你就可以在 Controller 中拥有多个 GetAll.

This way you can have multiple GetAll in Controller.

这里更重要的一点是,对于这种路由风格,您必须使用属性来指定允许的 HTTP 方法(如 [HttpGet]).

One more important thing here is that with this style of routing, you must use attributes to specify the allowed HTTP methods (like [HttpGet]).

还有一个选项可以将基于默认 Web API 动词的路由与传统方法混合使用,这里有很好的描述:

There is also an option of mixing the default Web API verb based routing with traditional approach, it is very well described here:

这篇关于Api 控制器声明多个 Get 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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