无法调用 WebApi 2 方法
Unable to call WebApi 2 method
我在我的项目中添加了一个 webapi 2 控制器,在 api > LoginAPI 中,如下所示:
在 LoginApi 内部,我有以下内容:
[RoutePrefix("api/LoginApi")]
public class LoginApi : ApiController
{
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
}
在我的 global.asax 文件中我有:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
里面 App_Start 我有以下内容:
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 }
);
}
然后我在 LoginAPI 和 运行 项目的 Get 方法中放置了一个断点,并在 URL 中键入以下内容:
http://localhost:37495/api/LoginApi/4
但我得到:
No HTTP resource was found that matches the request URI 'http://localhost:37495/api/LoginApi/4'.
所以我想好吧,让我这样指定方法名称
http://localhost:37495/api/LoginApi/Get/4
这个returns:
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
现在我已经看了一段时间,所以也许我错过了一些明显的东西,但如果有人能告诉我我做错了什么,我将不胜感激。
您设置的 routeTemplate
将适用于基于约定的路由,除了 Web API 在搜索控制器 [=26= 时添加字符串 "Controller" ](根据 this article)。因此,您需要重命名控制器 class LoginApiController
才能使基于约定的路由正常工作。
对于基于属性的路由,RoutePrefix
属性的添加应与操作中的 Route
属性结合使用。尝试将以下内容添加到控制器中的 Get
方法中:
[HttpGet]
[Route("{id}")]
然后导航到 http://localhost:37495/api/LoginApi/4
。
我在我的项目中添加了一个 webapi 2 控制器,在 api > LoginAPI 中,如下所示:
在 LoginApi 内部,我有以下内容:
[RoutePrefix("api/LoginApi")]
public class LoginApi : ApiController
{
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
}
在我的 global.asax 文件中我有:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
里面 App_Start 我有以下内容:
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 }
);
}
然后我在 LoginAPI 和 运行 项目的 Get 方法中放置了一个断点,并在 URL 中键入以下内容:
http://localhost:37495/api/LoginApi/4
但我得到:
No HTTP resource was found that matches the request URI 'http://localhost:37495/api/LoginApi/4'.
所以我想好吧,让我这样指定方法名称
http://localhost:37495/api/LoginApi/Get/4
这个returns:
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
现在我已经看了一段时间,所以也许我错过了一些明显的东西,但如果有人能告诉我我做错了什么,我将不胜感激。
您设置的 routeTemplate
将适用于基于约定的路由,除了 Web API 在搜索控制器 [=26= 时添加字符串 "Controller" ](根据 this article)。因此,您需要重命名控制器 class LoginApiController
才能使基于约定的路由正常工作。
对于基于属性的路由,RoutePrefix
属性的添加应与操作中的 Route
属性结合使用。尝试将以下内容添加到控制器中的 Get
方法中:
[HttpGet]
[Route("{id}")]
然后导航到 http://localhost:37495/api/LoginApi/4
。