2

but I am new to attribute routing, and I have no idea why this isn't working while everything else does so I have this

[RoutePrefix("api/statistics")]
 public class StatisticsController : ApiController

And then I have

 [HttpGet]
    [Route("categoryTagsByTotalIssues/{categoryId:int}")]
    public IHttpActionResult CategoryTagsByTotalIssues(int cateogryId)

Which when called from postman https://localhost:44363/api/statistics/categoryTagsByTotalIssues/3 returns a 404 but if I do https://localhost:44363/api/statistics/getTopFiveCategories which is something like this in code

 [HttpGet]
    [Route("getTopFiveCategories")]
    public IHttpActionResult GetTopFiveCategories()

It works, I have no idea why the other one doesn't can someone explain this to me?

klashar
  • 2,519
  • 2
  • 28
  • 38
Harry
  • 3,333
  • 3
  • 18
  • 28
  • This looks like a typo between `categoryId` in the route template and `cateogryId` in the action paramaters – Nkosi Mar 22 '17 at 00:05

2 Answers2

2

The comments in Sameer's answer correctly identify the issue as a typo with Category vs Catoegory. As you have seen, the name of the parameter in the method signature and the name of the parameter in the route need to exactly match.

I wanted to expand on this a bit in regards to parameter binding. Given that your category id is an int, which is a simple type, there is no need for [FromUri]. Let's say you had some sort of complex object being passed in and you wanted it to come in from the the URL as opposed to the body (if you were doing a POST, as GET's don't have a body). In this scenario you would need to explicitly decorate the parameter with [FromUri] as WebAPI2 automatically assumes that complex types originate from the body unless you specify otherwise.

The converse of this is true as well. Let's say you are POST'ing a simple thing, like an int, and it's in the body and not the URL. You would need to decorate the parameter with [FromBody] to tell WebAPI2 to fish that value out of the POST body and not from the URL, which it otherwise would do be default.

Bill Sambrone
  • 4,334
  • 4
  • 48
  • 70
1

Use this [Route("categoryTagsByTotalIssues")] And in parameter update this public IHttpActionResult CategoryTagsByTotalIssues(int categoryId)

tRuEsAtM
  • 3,517
  • 6
  • 43
  • 83
  • Still returns 404 is this because its not from an ajax call or something and am trying from postman? – Harry Feb 16 '17 at 17:46
  • @AvalothOath Just making sure, is there category id 3 present in your database or whatever in memory data structure you are using? – tRuEsAtM Feb 16 '17 at 17:52
  • Yes it is and i have simmilar routes all over my project which all work fine, so i have no idea why this doesn;t – Harry Feb 16 '17 at 17:52
  • 3
    Just check your spelling of the parameter `cateogryId`! It could be because of it! – tRuEsAtM Feb 16 '17 at 17:54
  • I don't believe i missed this haha thanks so much for this! – Harry Feb 16 '17 at 17:56