简体   繁体   中英

Web Api Routes picking generic over specific

Hi Guys i am new with web api routes and i have this issue where my call will pick up the more generic one over the specific one. The ajax call i have is

   $.getJSON("/api/solutions/GetSolutionByCategory/" + categoryId,
                        function (data) {//..some other functions}

Within the solutions controller there are 2 methods

     [HttpGet]
    public IHttpActionResult GetSolutionByCategory(int cateogryId)
    {
        List<Solution> solutions = _context.Solutions.Where(s => s.CategoryId == cateogryId).ToList();
        return Ok(solutions.Select(Mapper.Map<Solution, SolutionDto>));
    }
    [HttpGet]
    public IHttpActionResult GetSolutions()
    {
        return Ok(_context.Solutions.ToList().Select(Mapper.Map<Solution, SolutionDto>));
    }

And then i have the following 3 routes

        config.Routes.MapHttpRoute(
            name: "WithAction",
            routeTemplate: "api/{controller}/GetIssuesByFlag/{flag}",
            defaults: new {flag = 3}
        );
        config.Routes.MapHttpRoute(
            name: "SolutionByCategory",
            routeTemplate: "api/{controller}/GetSolutionByCategory/{categoryId}",
            defaults: new {categoryId = -1}
        );
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new {id = RouteParameter.Optional}
        );

What happens is that my ajax call will ignore the 2nd one that is the one i want it to hit and goes to the 3rd one there for instead of calling the GetSolutionsByCategory it hits the generic GetSolutions

What am i doing wrong here?

There is a typo in your action parameter name, its int cateogryId instead of int categoryId - public IHttpActionResult GetSolutionByCategory(int categoryId) .

However, I would suggest you to go for attribute routing instead of adding lots of route configurations. Enable attribute routing in your web api config class - config.MapHttpAttributeRoutes(); and in your controller:

[RoutePrefix("api")]
public class SolutionsController:ApiController
{

    [HttpGet]
    [Route("GetSolutionByCategory/{categoryId})"]
    public IHttpActionResult GetSolutionByCategory(int categoryId)
    {
        ....
    }

    [HttpGet]
    [Route("GetSolutions")]
    public IHttpActionResult GetSolutions()
    {
        ...
    }

}

Using Attribute routing we can have same controller with multiple get and post methods. We need to add the routing on the action methods.

We can provide the constraints as well with attribute routing.

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