0
votes

I can't seem to find an answer to this question so I'm posting it here. This may be a basic routing question and perhaps I'm just missing something obvious. I have a WebAPI2 project that has GetAll() method in the controller. I'm using Attribute Routing including a RoutePrefix. When I test the method using Postman it works fine http://localhost/api/v1/Suppressions and it returns a list of JSON from my Mongo DB collection. By chance during testing I happened to test and added a parameter to the URL thinking I would receive a "The resource cannot be found" error http://localhost/api/v1/Suppressions?name=abc but it instead called the GetAll() method.

During routing are parameters ignored and is the URI the only thing used (unless, of course, I have a method that specifically named the parameters like Get(string name))? If that's the case, is there a route constraint that I need to add to my GetAll() method in order to throw the "The resource annot be found" error if someone inadvertently called the method with a parameter or list of parameters?

2

2 Answers

0
votes

Query parameters are ignored in routing, unless they specified in the Uri. You can either add a separate route for 'Suppressions?name={name}' or handle it within your existing call.

For information on Uri matching, see: UriTemplate.Match

0
votes

It depends.

Let's say that you have a method like the one that you are describing. For example,

[RoutePrefix("api")]
public class api: ApiController {
    [HttpGet]
    [Route("Supressions")]
    public HttpResponseMessage GetAll(HttpRequestMessage request){
      ///etc
    }
}

This method will be called no matter what parameters you use.

However, if you do something like this

[RoutePrefix("api")]
public class api: ApiController {
    [HttpGet]
    [Route("Supressions/{abc}")]
    public HttpResponseMessage Get(HttpRequestMessage request, string abc){
      ///etc
    }
}

You will need the parameter. If you don't have it and you call http://localhost/api/Suppressions, it will return something like this:

{
"message": "No HTTP resource was found that matches the request URI 'http://localhost:64307/api/Suppressions'.",
"messageDetail": "No type was found that matches the controller named ''."
}

Now, when you have multiple parameters, you can do something like this, and if you don't use them in your call, it's going to complain as well

[RoutePrefix("api")]
public class api: ApiController {
    [HttpGet]
    [Route("Supressions")]
    public HttpResponseMessage Get(HttpRequestMessage request, string abc, int id, int somethingElse){
      ///etc
    }
}

Here the call would be something like this:

http://localhost:64307/api/Suppressions?abc=asdas&id=13&somethingElse=45

Hope this help you understand