2

I need to have a custom action for my api controller like api/{controller}/{action}/{id}

This is my config

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

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

This hit the default route /api/dropzone/1 But i try to hit /api/dropzone/browse/1 by the "ApiByAction" configuration, but it doesnt work.

1 Answer 1

6

The order of your route definitions is important, make sure you respect it, because they are evaluated in the same order in which you declared them:

config.Routes.MapHttpRoute(
    name: "ApiByAction",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional },
    constraints: new { action = @"^(?!\d)[a-z0-9]+$" }
);

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

Also notice that you might need to specify a constraint for the {action} token in the first route definition.

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

2 Comments

Sorry, this brokes the default route. The /api/{action}/{id} doesnt work.
You are right. You will have to specify a constraint for the {action} token in your first route definition. I have updated my answer to illustrate that. Here the action name cannot start with a number and can contain letters or numbers only and it has at least one character length.

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.