简体   繁体   中英

Why I get Get all instead of single when I make a request to a web API with a parameter

Why do I get All instead of the Single result when I do an HTTP request for a web API like this:

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

I think the second method should be executed but the first one is executed instead:

  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));

    }

If you've created a brand new ASP.Net (not core) Web API project in Visual Studio 2017 (I'm on 15.8.0), this is the default contents of 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 }
            );
        }
    }
}

You'll notice that it has a mapping for an id parameter, but no such mapping for campCode (hopefully, that isn't unexpected).

You can either add a separate route or change your parameter name. Or supply campCode as a query string parameter instead.


For any "why doesn't it call method X instead of Y", you should realise it's always a question of routes. There's a handy Route Debugger by Phil Haack which you can always add in and help with experimenting/answering this sort of question.

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