简体   繁体   English

无法从 ASP.NET Web API 获得任何响应

[英]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: WebApiConfig 文件:

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: Web API 在一个单独的项目中:

在此处输入图像描述

When I enter https://localhost:44361/api/comment/getcomments当我输入https://localhost:44361/api/comment/getcomments

I get this error:我收到此错误:

No HTTP resource was found that matches the request URI未找到与请求 URI 匹配的 HTTP 资源

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但您也可能必须修复控制器路由,因为它源自 ApiController,而不是控制器

[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)选项 1:您可以尝试使用按操作名称路由(链接中的文档并在此处解释)

With the default routing template, Web API uses the HTTP verb to select the action.使用默认路由模板,Web API 使用 HTTP 动词来选择操作。 However, you can also create a route where the action name is included in the URI:但是,您也可以创建一个路由,其中​​操作名称包含在 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.在此路由模板中,{action} 参数命名控制器上的操作方法。 With this style of routing, use attributes to specify the allowed HTTP verbs .使用这种路由风格,使用属性来指定允许的 HTTP 动词 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.在这种情况下,“ api/Comment/GetComments/1 ”的 GET 请求将映射到 GetComments 方法。

Option 2: You can also use the Routing Tables o determine which action to invoke, the framework uses a routing table.选项 2:您还可以使用路由表来确定调用哪个操作,框架使用路由表。

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:一旦找到匹配的路由,Web API 就会选择控制器和操作:

  • To find the controller, Web API adds "Controller" to the value of the {controller} variable.为了找到控制器,Web API 将“Controller”添加到 {controller} 变量的值中。
  • 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 .为了找到动作,Web API 会查看HTTP 谓词,然后查找名称以该 HTTP 谓词名称开头的动作 For example, with a GET request, Web API looks for an action prefixed with " Get ", such as " Get Comment" or "GetAllComments".例如,对于 GET 请求, Web API 会查找以Get ”为前缀的操作,例如“ Get Comment”或“GetAllComments”。 This convention applies only to GET , POST , PUT , DELETE , HEAD, OPTIONS, and PATCH verbs.此约定仅适用于GETPOSTPUTDELETE 、 HEAD 、 OPTIONS 和 PATCH 动词。

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 请求,以及为每个请求调用的操作:

HTTP Verb | HTTP 动词 | URI Path | URI 路径 | Action |行动 | Parameter范围

  • GET |获取 | api/Comment | api/评论| GetAllComments |获取所有评论 | (none) (没有任何)
  • GET |获取 | api/Comment/4 | api/评论/4 | GetCommentById | GetCommentById | 1 1
  • DELETE |删除 | api/Comment/4 | api/评论/4 | DeleteComment |删除评论 | 1 1
  • POST |发布 | api/Comment | api/评论| (no match) (不匹配)

Notice that the {id} segment of the URI, if present, is mapped to the id parameter of the action.请注意,URI 的{id}段(如果存在)映射到操作的id参数。 In this example, the controller defines two GET methods, one with an id parameter and one with no parameters.在这个例子中,控制器定义了两种 GET 方法,一种带有 id 参数,一种没有参数。

Also, note that the POST request will fail, because the controller does not define a "Post..." method.另外,请注意 POST 请求将失败,因为控制器没有定义“Post...”方法。

You need to send the id in the url.您需要在 url 中发送 id。 For example: https://localhost:44361/api/comment/getcomments?id=1234例如: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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法从ASP.NET Web API获得响应 - Can't get response from ASP.NET web API 在 Asp.net web API 和 Z03D476861AFD384510F2CB081 上使用 localhost 时无法得到响应 - Can't get a response back when using localhost on Asp.net web API and postman 试图从 ASP.NET Web API 获取文件响应 - Trying to get file response from ASP.NET Web API 如何从Asp.Net Web Api 2获得类似于Google API响应的JSON结果? - How can I get JSON result from Asp.Net Web Api 2 that looks like Google API response? 尝试从asp.net Web API调用获取响应时,Android Studio中出现超时异常 - Timeout exception in android studio while trying to get a response from an asp.net web api call 如何从 ASP.NET Core Web API 向客户端发送 JSON 响应? - How can I send JSON response to client from ASP.NET Core Web API? 无法使CORS适用于ASP.NET Core Web API - Can't get CORS working for ASP.NET Core Web API 继承Controller时无法使Route在ASP.Net Web API 2中工作 - Can't get Route to work in ASP.Net Web API 2 when inheriting Controller Sending class data as JSON array format for GET request Response in ASP.Net Dot Core Web API ( GET response data from Web API) - Sending class data as JSON array format for GET request Response in ASP.Net Dot Core Web API ( GET response data from Web API) 从ASP.NET Web API获取可反序列化的DateTime - Get deserializable DateTime from ASP.NET Web API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM