简体   繁体   中英

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

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?

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

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:

routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);

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:

public class CommentController : ApiController
{
    [HttpGet] // Attribute to specify the allowed HTTP verbs
    public string GetComments(int id);
}

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.

routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

Once a matching route is found, Web API selects the controller and the action:

  • To find the controller, Web API adds "Controller" to the value of the {controller} variable.
  • To find the action, Web API looks at the HTTP verb, and then looks for an action whose name begins with that HTTP verb name . For example, with a GET request, Web API looks for an action prefixed with " Get ", such as " Get Comment" or "GetAllComments". This convention applies only to GET , POST , PUT , DELETE , HEAD, OPTIONS, and PATCH verbs.

sample:

public class CommentController : ApiController
{
    public IEnumerable<Comment> GetAllComments() { }
    public Comment GetCommentById(int id) { }
    public HttpResponseMessage DeleteComment(int id){ }
}

Here are some possible HTTP requests, along with the action that gets invoked for each:

HTTP Verb | URI Path | Action | Parameter

  • GET | api/Comment | GetAllComments | (none)
  • GET | api/Comment/4 | GetCommentById | 1
  • DELETE | api/Comment/4 | DeleteComment | 1
  • POST | api/Comment | (no match)

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.

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

[RoutePrefix("api/Comment")] //routeprefix bind before url every action//you can use Route also 
public class CommentController : ApiController
{
    private readonly ICommentRepository _commentRepository;

    public CommentController(ICommentRepository commentRepository)
    {
        _commentRepository = commentRepository;
    }

    [Route("{id:int}")] //or//[Route("~/api/**meaningfulRelatedname**/{id:int})]
    [HttpGet]
    public IHttpActionResult GetComments(int Id)
    {
        var comments = _commentRepository.GetComments(Id);
        return Ok(comments);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM