【问题标题】:MVC Web Api calling method not working properlyMVC Web Api 调用方法无法正常工作
【发布时间】:2014-05-08 11:49:43
【问题描述】:

我正在尝试实现三个方法控制器

public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        public IEnumerable<string> Get(int id)
        {
            return new string[] { "sa1", "sa2" };
        }
        [HttpGet]
        public IEnumerable<string> password()
        {
            return new string[] { "password", "password" };
        }
 config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

但是当我尝试打电话给http://localhost:49365/api/mycontrollername/password

总是显示请求无效。

【问题讨论】:

  • 你能告诉我们你的路由配置吗?另外,您得到的确切错误是什么? (即 404 未找到)。
  • 不行,我已经用config.Routes.MapHttpRoute替换了默认路径(名称:“DefaultApi”,routeTemplate:“api/{controller}/{action}/{id}”,默认值:new { id = RouteParameter.Optional });

标签: asp.net-mvc asp.net-web-api


【解决方案1】:

如果你想调用像"http://localhost:49365/api/mycontrollername/password"这样的api函数

你必须在控制器上添加 ActionName 属性并在 Routeconfig.cs 上添加路由;

这里是例子

    [ActionName("GetEmployees")]
    public IEnumerable<Employee> GETEmployees()
    {
        return _db.Employees.AsNoTracking();
    }

   routes.MapRoute(
            name: "Default",
            url: "api/{controller}/{action}/{id}",
            defaults: new { controller = "Employees", action = "GetEmployees", id =     UrlParameter.Optional }
        );

【讨论】:

  • 我已经做到了,先生,但非常感谢您抽出宝贵的时间回答
【解决方案2】:

我怀疑它正在尝试调用Get(int id),然后尝试将单词“password”作为整数参数传递。据我所知,这归结为约定优于配置,因为当您发出 GET 请求时,它会查找名为 Get 的方法。在这种情况下,它会找到一个。然后基于路由,即在控制器名称带有 ID 之后,它查看 URL 的下一部分,在本例中为“密码”,然后将其用作 id 参数的值。

如果您要删除两个 Get 方法,您可能会发现您的 URL 有效,但如果您添加其他 HttpGet 方法,您将遇到与“找到多个操作”相关的其他问题。如果您决定需要多个 HttpGet 方法,以下讨论可能会有所帮助:

Web Api Routing for multiple Get methods in ASP.NET MVC 4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 2021-04-15
    • 2012-06-14
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多