【问题标题】:Unable to call WebApi 2 method无法调用 Web Api 2 方法
【发布时间】:2016-04-08 10:13:27
【问题描述】:

我已经在我的项目中添加了一个 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

这会返回: The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

现在我已经研究了一段时间,所以也许我错过了一些明显的东西,但如果有人能告诉我我做错了什么,我将非常感激。

【问题讨论】:

    标签: asp.net-web-api2 asp.net-mvc-routing url-routing


    【解决方案1】:

    您设置的routeTemplate 将适用于基于约定的路由,除了Web API 在搜索控制器类时添加字符串“Controller”(根据this article)。因此,您需要重命名您的控制器类 LoginApiController 以使基于约定的路由工作。

    对于基于属性的路由,添加RoutePrefix 属性应与您的操作中的Route 属性结合使用。尝试将以下内容添加到控制器中的 Get 方法中:

    [HttpGet]
    [Route("{id}")]
    

    然后导航到http://localhost:37495/api/LoginApi/4

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-08
      • 2016-08-03
      • 2014-12-11
      • 2016-11-16
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 2015-08-24
      相关资源
      最近更新 更多