briantist
briantist

Reputation: 47772

ASP.NET Web Api 2 - Attribute Based Routing - How do I force a parameter to query string only?

I am working on a Web Api 2 project and I am using attribute based routing. Here is a sample route:

[Route("{id:int}", Name = "GetEmployeeById")]
[HttpGet]
public IHttpActionResult GetEmployee(int id)
{
    ...
}

This works with the following URLs:

What I would prefer is that the first form (the parameter in the URI), would not be allowed, and only the second form (query string) would work.

What I've Tried

Mostly, I've tried searching the web for a way to make this work, and I'm not finding much.

This page talks about route constraints but this syntax doesn't seem to work (anymore?).

This page doesn't actually prevent the URI form from working.

Upvotes: 0

Views: 1147

Answers (3)

Omar.Alani
Omar.Alani

Reputation: 4130

There is an attribute called "[FromUri]" that you can use to decorate a method parameter, and the model binder will try to look for that parameter from the Querystring, it may not help you with this scenario but it is good to know about it, so in case you want to pass a search options for example to a Get method.

Hope that helps.

Upvotes: 1

briantist
briantist

Reputation: 47772

Actually, I was wrong about my original code. The query string parameter did not work with the route I specified. Instead, I could do this:

[Route("", Name = "GetEmployeeById")]
[HttpGet]
public IHttpActionResult GetEmployee(int id)
{
    ...
}

And this will do what I want. It must be getting the name id from the function's parameter list.

Unfortunately, this means I can't put a constraint on it anymore, but I guess I can just validate within the function.

Upvotes: 0

MiBu
MiBu

Reputation: 869

Couple of ways to achieve this. Here are some options

  1. Rename parameter to something else than id (eg. employeeId).
  2. Change the default routing configuration in WebApiConfig:

        //Default configuration, you can see here the "id" parameter which enables action/id matching
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        //It should look like this
        config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}"
            );
    

Also you can do it with custom attributes.

Upvotes: 0

Related Questions