找不到与请求 URI 匹配的 HTTP 资源 'http://localhost/api/GetById/2'
No HTTP resource was found that matches the request URI 'http://localhost/api/GetById/2'
很多人问过同样的问题,但我找不到解决问题的方法。
在邮递员中,当我调用“http://localhost/api/GetById/2”时,出现以下错误
No HTTP resource was found that matches the request URI 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;
}
有人能告诉我我做错了什么吗?
将您的路线更改为:
[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)
将steve
替换为控制器名称。您正在混合属性路由和基于约定的路由。这导致路由表呕吐。由于您使用路由 ~/api/getbyid/
它不再具有来自基于约定的路由的控制器引用。因此,您需要执行所有属性路由或所有基于约定的路由。
此外,您没有在路由的末尾使用 int
,因此 .net 路由器无法解析查询字符串并将您的 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;
}
}
很多人问过同样的问题,但我找不到解决问题的方法。
在邮递员中,当我调用“http://localhost/api/GetById/2”时,出现以下错误
No HTTP resource was found that matches the request URI 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;
}
有人能告诉我我做错了什么吗?
将您的路线更改为:
[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)
将steve
替换为控制器名称。您正在混合属性路由和基于约定的路由。这导致路由表呕吐。由于您使用路由 ~/api/getbyid/
它不再具有来自基于约定的路由的控制器引用。因此,您需要执行所有属性路由或所有基于约定的路由。
此外,您没有在路由的末尾使用 int
,因此 .net 路由器无法解析查询字符串并将您的 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;
}
}