简体   繁体   English

具有自定义操作的API控制器

[英]API Controller with custom action

I need to have a custom action for my api controller like api/{controller}/{action}/{id} 我需要为自己的api控制器执行自定义操作,例如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. 这命中了默认路由/ api / dropzone / 1,但是我尝试通过“ ApiByAction”配置命中/ api / dropzone / browse / 1,但是它不起作用。

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. 还要注意,您可能需要在第一个路由定义中为{action}令牌指定一个约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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