Home > OS >  Can't get any response from ASP.NET Web API
Can't get any response from ASP.NET Web API

Time:06-18

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:

enter image description here

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?

CodePudding user response:

you have to fix a route template, and fix an action route

[Route("{id}")]
public IHttpActionResult GetComments(int Id)

but it is possible that you will have to fix a controller route too, since it derives from ApiController, not a Controller

[Route("~/api/[controller]/[action]")]
public class CommentController : ApiController

CodePudding user response:

You need to send the id in the url. For example: https://localhost:44361/api/comment/getcomments?id=1234

  • Related