当我使用参数向 Web API 发出请求时,为什么我得到全部而不是单个

Anyname 不关心

当我对这样的 Web API 发出 HTTP 请求时,为什么我得到All而不是Single结果:

http://localhost/HR/api/camps/2

我认为应该执行第二种方法,但执行第一种方法:

  public IHttpActionResult GetCamps()
    {
        var  camps = _context.CAMPs.ToList()
                    .Select(Mapper.Map<CAMP, CampDTO>);
        return Ok(camps);

    }

    public IHttpActionResult GetCamp(int campCode)
    {
        var camp = _context.CAMPs
            .SingleOrDefault(c => c.CAMP_CODE == campCode);

        if (camp == null)
            return NotFound();

        return Ok(Mapper.Map<CAMP, CampDTO>(camp));

    }
Damien_The_Unbeliever

如果您在 Visual Studio 2017 中创建了一个全新的 ASP.Net(非核心)Web API 项目(我使用的是 15.8.0),这是以下的默认内容WebApiConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace WebApplication1
{
    public static class 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 }
            );
        }
    }
}

你会注意到它有一个id参数的映射,但没有这样的映射campCode(希望这不是意外)。

您可以添加单独的路由或更改参数名称。或者campCode作为查询字符串参数提供。


对于任何“为什么不调用方法 X 而不是方法 Y”,您应该意识到这始终是路由问题。Phil Haack 提供了一个方便的Route Debugger,您可以随时添加它并帮助试验/回答此类问题。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

当我向ASP.NET CORE中的Web API控制器发送多部分请求时,使用哪种格式程序?

为什么我的 Web API 不响应我的请求?

当我添加其他参数时,无法连接到ASP.NET Web API

当我从 Android 向 Flask Web 服务发送参数时,如何解决“SSL 库失败”?

当我向 api 服务器发出 post 请求时收到 404 错误

为什么我可以从浏览器而不是Angular的资源发出REST API请求?

为什么当我使用 node.js 将整数作为参数放入 url 时,我的 RESTful API 卡住了

当我通过 UI 向 api 端点发出 GET/POST 请求时,如何发送我的 JWT 令牌?

当我不完全接受REST时应该使用Web API

当我尝试使用 GET 方法时,私有 Web API 的授权问题

为什么只有在设置了 Content-Type HTTP 标头时,对我的 Web API 的请求才会成功?

使用python向Stackoverflow API发出请求时,如何通过标头传递我的API密钥

为什么在使用 web2py 向外部 API 发出后请求时出现“实例没有属性 _caller”错误

为什么我的简单RoutePrefix无法使用Web API?

当我尝试用Postman测试我的API时为什么没有传递任何参数?

当我尝试使用json从Web服务中获取数据时,data参数为nil

我如何向API发出请求

为什么我在 flutter_web 中更新 HtmlView 时得到 _state != _PlatformViewState.disposed 不是真正的异常?

反应。为什么当我在请求后请求 api 时在我调用的浏览器 url 中出现 api

向R发出多个Web API请求的信号

当我的托管阻止它时,如何向 Telegram API 发送请求?

当我向/ api / users / login发送POST请求时,用户未定义

为什么我的Web API路由不起作用?

为什么我的 Web API 不返回 JSON?

我应该使用Web API与Web方法吗?

为什么我从 Web API 调用方法时收到数组 JSON 响应?

当我向脚本传递参数时,使用gets()会给出“无此类文件或目录”错误

Web ApI:HttpClient没有调用我的Web API操作

Web API 2在长id参数上给了我404