访问ASP.NET Web API提示无匹配请求URI的HTTP资源怎么办
问题描述
我的控制器代码如下:
public class CommentController : ApiController { private readonly ICommentRepository _commentRepository; public CommentController(ICommentRepository commentRepository) { _commentRepository = commentRepository; } public IHttpActionResult GetComments(int Id) { var comments = _commentRepository.GetComments(Id); return Ok(comments); } }
WebApiConfig配置文件代码如下:
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 } ); }
该Web API为独立项目中的服务:
当访问地址https://localhost:44361/api/comment/getcomments时,收到如下错误提示:
No HTTP resource was found that matches the request URI(找不到与请求URI匹配的HTTP资源)
请问是哪处配置有误导致该问题,该如何修复?
错误原因
核心问题是路由配置和请求URL规则不匹配:
你当前配置的默认Web API路由模板为api/{controller}/{id},没有设置{action}(方法名)路由段,这是Web API默认的REST风格路由规则,会直接根据HTTP请求方法(GET/POST/PUT/DELETE)匹配控制器上对应命名前缀的方法,不会识别URL路径中写的getcomments作为方法名。
另外你定义的GetComments方法要求必须传入int类型的Id参数,当前访问的URL没有携带该必填参数,即便路由匹配成功也会因为参数缺失触发错误。
修复方案
两种方案选其一即可,不要混合使用避免路由冲突:
- 方案1:沿用默认路由规则,修改请求URL
保持现有路由配置不变,按照默认规则发起GET请求,直接访问https://localhost:44361/api/comment/1(把路径最后一段的1替换为你实际需要查询的评论Id),不要在URL中添加方法名getcomments。Web API会自动识别GET请求,匹配到CommentController中的GetComments方法,同时将路径最后一段的数值绑定到方法的Id参数上。 - 方案2:修改路由规则,支持URL携带方法名
如果你确实需要在URL中体现Action方法名,就修改WebApiConfig中的默认路由配置,增加{action}路由段:
修改完成后,访问地址需要携带必填的Id参数,格式为config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } );https://localhost:44361/api/comment/getcomments/1即可正常匹配接口。
注意:C# Web API路由参数绑定对大小写敏感,方法定义的参数名为大写Id,传参时需要保持名称大小写一致,否则会出现参数绑定失败的问题。
内容的提问来源于stack exchange,提问作者ELOL
相关产品推荐
相关产品推荐

