【问题标题】:Broken Routing/Action in Web APIWeb API 中的路由/操作损坏
【发布时间】:2013-04-18 01:15:01
【问题描述】:

我在 WebApiConfig.cs 中定义了我的默认路由:

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional, page = 20, offset = 0 }
        );

在我的控制器中,我有一个动作:

    // GET api/users
    [HttpGet]
    public IEnumerable<User> Get(string id, int page, int offset)
    {
        return id != null 
            ? new User[]{Get(id)} 
            : _userService.All().Skip(offset*page).Take(page);
    }

我知道这是最近工作的,但现在我收到了臭名昭著的“在控制器'用户'上找不到与请求匹配的操作”错误。我似乎无法弄清楚(如果有的话)发生了什么变化。自从添加页面/偏移的默认值以来,我已经撤消了所有更改,但仍然没有。

有什么想法吗?

请求网址:http://localhost/api/api/Users

【问题讨论】:

标签: c# c#-4.0 asp.net-web-api asp.net-web-api-routing


【解决方案1】:

这里的参数“id”是可选的,但是动作选择器希望在动作上为其指定一个默认值。

public IEnumerable Get(string id = null, int page, int offset)

还有关于网址,可能是错字,你的意思是http://localhost/api/Users 而不是http://localhost/**api/api**/Users

【讨论】:

  • 将路由 def 更新为 id = "" 而不是 id = RouteParameter.Optional 似乎让它再次工作。现在我需要看看结果是什么损坏了。
【解决方案2】:

您尚未在路线中指定操作。您要么需要在 URL 中添加 {action} 片段,要么在 default 对象中指定操作。

【讨论】:

  • 不太可能如图所示的注册是default 一个用于Web-API(注意MapHttpRoute - 不是MapRoute
  • @AlexeiLevenkov:你仍然需要采取行动。 WebAPI 的默认路由也包含一个。
  • 路线中从未有任何动作。这是 mvc 4 web api 项目的默认设置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-10
  • 2013-05-12
  • 2018-01-01
  • 2013-06-15
  • 2018-09-17
  • 1970-01-01
  • 2016-12-07
相关资源
最近更新 更多