0

My WebApi.config looks like this:

config.MapHttpAttributeRoutes();
    config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

which means it is configured to support both attribute based routing and conventional routing.

And the sample controller created:

[RoutePrefix("v1")]
public class Values1Controller : ApiController
{
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };

    }

    [Route("products")]
    public string Get(int id)
    {
        return "value";
    }
}

When I invoke http://localhost.domain/api/values1/v1/ the response is value1, value2

But, when I try to invoke http://localhost.domain/api/values1/v1/products/1 (notice the products attribute route on the public string Get(int id) method, the break point is not hit.

In other words, how to call the public string Get(int id) method with the attribute routing Route(products) on top of it?

1 Answer 1

3

You use /v1/products?id=10 to hit the action public string Get(int id) or change your route template to be [Route("products/{id}")] to make request like /v1/products/10

Note that attributed controllers/actions cannot be reached by requests which match conventional routes, so that means you cannot do something like api/values/1 to reach public string Get(int id) action

Sign up to request clarification or add additional context in comments.

2 Comments

Great. Worked like a charm. Thanks a lot
http://localhost:portNum/v1/products?id=10 hits the breakpoint when the routing attribute is [Route("products")]. http://localhost:portNum/v1/products/10 hits the breakpoint when the routing attribute is [Route("products/{id}")]. Nice explanation @Kiran. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.