代码之家  ›  专栏  ›  技术社区  ›  Learning Curve

未找到与请求URI匹配的HTTP资源'http://localhost/api/GetById/2'

  •  1
  • Learning Curve  · 技术社区  · 7 年前

    很多人都问过同样的问题,但我找不到解决问题的方法。

    当我叫邮递员的时候 http://localhost/api/GetById/2 '我得到以下错误

    未找到与请求URI匹配的HTTP资源 http://localhost/api/GetById/2 .

    当我将值2作为查询字符串传递时,它可以正常工作 http://localhost/api/GetById/?id=2 . 以下是我的WebApiConfig路由参数设置:-

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

    以下是我的API控制器操作方法

        [Route("~/api/GetById/")]
        [HttpGet]
        public HttpResponseMessage Get(int id)
        {
            var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(JsonConvert.SerializeObject(GetUsers(id)), "application/json");
    
            return response;
        }
    

    有人能告诉我我做错了什么吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Jamie Rees    7 年前

    将路线更改为:

    [Route("~/api/GetById/{id}")]
    

    看到这个了吗 https://blogs.msdn.microsoft.com/webdev/2013/10/17/attribute-routing-in-asp-net-mvc-5/

    您还可以非常具体地告诉代码 id 通过使用 [FromRoute] 属性如下:

      public HttpResponseMessage Get([FromRoute]int id)
    
        2
  •  0
  •   gh9    7 年前

    代替 steve 控制器名称。您正在混合属性路由和基于约定的路由。这导致routetable呕吐。因为你用的是路线 ~/api/getbyid/ 它不再具有来自基于约定的路由的控制器引用。因此,您需要执行全属性路由或基于所有约定的路由。

    此外,你没有承担 int 在你的路线的尽头,所以。net router无法分析查询字符串并将 integer 进入函数调用。

    [RoutePrefix("api/Steve")]
    public class SteveController :ApiControlller
    {
        [Route("GetById/{id:int}")]
        [HttpGet]
        public HttpResponseMessage Get(int id)
        {
            var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(JsonConvert.SerializeObject(GetUsers(id)), "application/json");
    
            return response;
        }
    }