Skip to main content
 首页 » 编程设计

c#之Web API 中损坏的路由/操作

2024年02月13日30tintown

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

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

在我的 Controller 中,我有一个 Action :

    // 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); 
    } 

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

有什么想法吗?

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

请您参考如下方法:

此处参数“id”是可选的,但 Action 选择器希望在 Action 上为其指定一个默认值。

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

另外关于 url,可能是错字,你的意思是 http://localhost/api/Users 而不是 http://localhost/**api/api**/Users