在 Web 窗体应用程序中使用 WebApi

Working with WebApi in a Web Forms application

我正在尝试在我的 Web 窗体应用程序中添加 WebApi(Visual Studio 2015,.NET 4.6)。我在其中添加了 App_Start 文件夹和 WebApiConfig.cs 如下(几乎是从 MVC 应用程序复制的):

public class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        // Adding routes for WebApi controllers
        RouteTable.Routes.MapHttpRoute(
            name: "SearchApi",
            routeTemplate: "api/search",
            defaults: new { controller = "SearchController" }
            );

    }
}

然后,我创建了一个文件夹 Controllers/WebApi 并添加了 SearchController.cs:

namespace IdeaMaverick.Web.Controllers.WebApi
{
    public class SearchController : ApiController
    {
        public IEnumerable<string> Get()
        {
            return new [] { "value1", "value2" };
        }
    }
}

但是当我在浏览器中点击 http://example.com/api/search 时,出现了这个错误:

{"message":"No HTTP resource was found that matches the request URI 'http://www.example.com/api/search'.","messageDetail":"No type was found that matches the controller named 'SearchController'."}

我显然遗漏了一些东西,但我不知道是什么。

我发现了问题 - 在路由的默认设置中,我必须指定省略 "Controller" 的控制器名称,所以它必须像

defaults: new { controller = "Search" }