我有一个带有此路由的 mvc 应用程序:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}
我的 Controller 可在以下位置访问:
http://localhost:1234/Test/Version
现在,我想向这个 mvc 应用程序添加一个 web api。 假设它叫做 TestWebAPIController 但是,我无法访问它
http://localhost:1234/TestWebAPI
或
http://localhost:1234/TestWebAPI/Get
我该如何解决这个问题? 我已经尝试将路线更改为
url: "{controller}/{id}",...
更新: 我尝试添加一个 WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
并尝试添加
GlobalConfiguration.Configure(WebApiConfig.Register);
到 Global.asax.cs 但我收到语法错误... 在 WebConfig.cs 中,它提示:
config.MapHttpAttributeRoutes();
并说不包含 MapHttpAttributeRoutes 的定义 在 Global.asax.cs 中,它提示
GlobalConfiguration.Configure(WebApiConfig.Register);
并说 System.Web.Http.GlobalConfiguration 不包含“配置”的定义
更新: 安装 webapi 后:
Install-Package Microsoft.AspNet.WebApi.WebHost
错误消失了,但我仍然无法路由到我的 webapi。
更新: 终于让它工作了。 在 global.asap.cs 中,您必须将 webapi 路由放在 BEFORE mvc 路由中,如下所示:
GlobalConfiguration.Configure(WebApiConfig.Register);
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
还需要更改:
routeTemplate: "api/{controller}/{id}"
到
routeTemplate: "api/{controller}/{action}/{id}"
请您参考如下方法:
Web API 不使用与 MVC 相同的路由。如果你在 Visual Studio for Web API 中启动一个新项目,或包含 Web API,你将在 App_Start 文件夹下看到一个名为 WebApiConfig.cs 的文件。这是您的 Web API 路由的去向。这些路由是通过此类的 Register() 方法注册的,使用传入的 HttpConfiguration 对象:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//other stuff
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/v1/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//other stuff
}
}
请注意,我还在路由前添加了“api/v1/”。这或类似的东西通常是一种很好的做法,这样您就可以根据需要对 api 进行版本控制,而不会影响使用旧版 api 的代码。
