3

I studied how to use APIs in a MVC project but I have some doubts about. (I'm writing in C# language before anyone asks).

So far, I know that the Api's route configuration is set in the WebApiConfig class and by default the route is:

routeTemplate: "api/{controller}/{id}"

By doing this, when I compile a jSon request I know what URI I have to call in order to obtain a specific result.
But I'd like to be more specific so I modified the Api's route to:

routeTemplate: "api/{controller}/{action}/{id}"

With this route I will be able to build an URI directly to a specific action (method?) inside my ApiController.

Also I learned that the /{controller}/, while building the URI with jSon, is the name of the class. That is, if the class is ProductsController the controller name that I have to use to build the URI is just /products. (So the whole URL will be /api/products).

Here questions are:
If I have an ApiController class named just Products, is it recognizable as part of an URI? Or the ApiController class have to end with "Controller"?
By following a tutorial I put my ApiController il the same folder as other Controllers. I know that is possible to put Apis into different folders. So, is every single API automatically recognized by MVC? I mean, wherever I save them, are they recognized as API?
If so, could I eventually call an API located in a different project than the one I'm working on?
Can I create a single project (as class library) with a collection of APIs?
Does the route configuration change if I want to call an API in a distinct project?

4

2 回答 2

6

哦,这是很多问题... :)

回答他们:

如果我有一个名为 Products 的 ApiController 类,它是否可以识别为 URI 的一部分?还是 ApiController 类必须以“Controller”结尾?

ASP.NET 路由使用该约定,因此,据我所知,如果您根据自己的喜好命名类,而不遵循该约定,它们将不会被识别,您很可能会得到 404。所以要回答您的问题,是的,名称必须以 结尾Controller,除非您覆盖默认约定(请参阅 Mike Goodwin 答案)。

按照教程,我将我的 ApiController 放在与其他控制器相同的文件夹中。我知道可以将 APIs 放入不同的文件夹中。那么,MVC 会自动识别每一个 API 吗?我的意思是,无论我将它们保存在哪里,它们是否被识别为 API?

文件夹无关紧要,ASP.NET 会查找与名称匹配的类。Api 控制器被识别为 API 控制器,因为它们继承自基础ApiController而不是控制器之一

如果是这样,我最终是否可以调用位于与我正在处理的项目不同的项目中的 API?我可以使用一组 API 创建一个项目(作为类库)吗?如果我想在不同的项目中调用 API,路由配置会改变吗?

这不清楚......你是什么意思“调用”一个API?如果 API 在另一个项目中,它可能会位于一个单独的地址上......您只需将您的 JSON 请求定向到该地址,因此如果您使用的是 jQuery,请执行以下操作:

$.getJSON('http://other.server/api/Controller', function(data) { ... });

而不仅仅是这样:

$.getJSON('/api/Controller', function(data) { ... });

(请注意跨站点脚本问题)。

希望这可以为您解决问题。随意询问某些东西是否有意义......

于 2013-09-13T15:28:27.693 回答
3

在 ASP.Net MVC 中,您可以通过实现自定义控制器工厂来完全控制控制器位置和实例化。

这是一个实现IControllerFactory接口的类。这提供了基于传入请求上下文选择和实例化控制器的方法。它还具有其他控制器生命周期行为的方法。

您在标准 MVC 中看到的基于名称约定的行为只是编码到默认控制器工厂的逻辑(它的类型DefaultControllerFactory很有趣)

下面是一个如何做一个客户控制器工厂的例子:

http://www.mgolchin.net/posts/18/dive-deep-into-mvc-icontrollerfactory

所以你的问题的答案是肯定的,你可以做任何你想做的事,但是不,这不是自动的。

于 2013-09-13T15:25:58.420 回答