简体   繁体   中英

API Controller with custom action

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM