当我对Web API进行HTTP请求时,为什么我得到All
而不是Single
结果:
我认为应该执行第二种方法,但是应该执行第一种:
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));
}
答案 0 :(得分:4)
如果您已在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,您可以随时添加它并帮助您尝试/回答此类问题。