My controller:
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 file:
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 }
);
}
The Web API is in a separate project:
When I enter https://localhost:44361/api/comment/getcomments
I get this error:
No HTTP resource was found that matches the request URI
What am I doing wrong here?
4
Answers
you have to fix a route template, and fix an action route
but it is possible that you will have to fix a controller route too, since it derives from ApiController, not a Controller
You need to send the id in the url. For example: https://localhost:44361/api/comment/getcomments?id=1234
Option 1: You can try to use the Routing by Action Name (Docs in link and explained here)
With the default routing template, Web API uses the HTTP verb to select the action. However, you can also create a route where the action name is included in the URI:
In this route template, the {action} parameter names the action method on the controller. With this style of routing, use attributes to specify the allowed HTTP verbs. For example, suppose your controller has the following method:
In this case, a GET request for "
api/Comment/GetComments/1
" would map to the GetComments method.Option 2:
You can also use the Routing Tables
o determine which action to invoke, the framework uses a routing table.
Once a matching route is found, Web API selects the controller and the action:
sample:
Here are some possible HTTP requests, along with the action that gets invoked for each:
HTTP Verb | URI Path | Action | Parameter
Notice that the {id} segment of the URI, if present, is mapped to the id parameter of the action. In this example, the controller defines two GET methods, one with an id parameter and one with no parameters.
Also, note that the POST request will fail, because the controller does not define a "Post…" method.