Search code examples
c#asp.net-web-apiasp.net-apicontrollermvcroutehandler

Multiple C# WebAPI API routes - restrict API method to one of the routes


I have multiple routes for my API like

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{token}/{controller}/{action}",
    defaults: null,
    constraints: null,
    handler: HttpClientFactory.CreatePipeline(
                new HttpControllerDispatcher(config),
                new DelegatingHandler[] { new ApiTokenValidator() })
);
config.Routes.MapHttpRoute(
    name: "LoginApi",
    routeTemplate: "api/{controller}/{action}",
    defaults: null,
    constraints: null,
    handler: HttpClientFactory.CreatePipeline(
                new HttpControllerDispatcher(config),
                new DelegatingHandler[] { new ApiLoginHandler() })
);

How can I make sure that a method in my APIController only can be used by for example the LoginApi route/handler?


Solution

  • Like Uriil commented on the question, the answer is to use attribute routing.

    As of http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#add-routes

    In my Example I use it like this to restrict the AddUser method to only be used with the wordpress api

    [Route("api/wordpress/shared/AddUser")]
    [HttpPost]
    public Object AddUser(string username)
    {
    }