Reputation: 16440
I currently have:
config.Routes.MapHttpRoute(
name: "AccountApiCtrl",
routeTemplate: "/api" + "/account/{action}/{id}",
defaults: new { controller = "accountapi", id = RouteParameter.Optional }
);
Which sends /api/account/myaction requests to accountapi controller. (it works great :-))
However, I'd rather not do this for each controller I have, is there a way I can use regex here so that I only have on declaration?
I.E so:
/api/account/action goes to controller: AccountApi and /api/user/action goes to controller: UserApi
i.e something along the lines of:
config.Routes.MapHttpRoute(
name: "ControllerApiMap",
routeTemplate: "/api" + "/{controller}/{action}/{id}",
defaults: new { controller = "{controller}+api", id = RouteParameter.Optional }
);
Upvotes: 4
Views: 1376
Reputation: 5588
Please, change as per below where you will be change regex:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // Route Pattern
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Default values for parameters
new { controller = "^H.*", action = "^Index$|^Contact$" } //Restriction for controller and action
);
Here, controller name start with H like Home and action start with Index or Contact, other's are ristricted.
Upvotes: 0
Reputation: 57999
Following is one way of achieving this:
config.Services.Replace(typeof(IHttpControllerSelector), new CustomHttpControllerSelector(config));
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
public class CustomHttpControllerSelector : DefaultHttpControllerSelector
{
public CustomHttpControllerSelector(HttpConfiguration config)
: base(config)
{
}
public override string GetControllerName(HttpRequestMessage request)
{
IHttpRouteData routeData = request.GetRouteData();
if (routeData.Values.ContainsKey("controller"))
{
return routeData.Values["controller"] + "api";
}
return base.GetControllerName(request);
}
}
Upvotes: 4