0

I have a following route:

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

I want this route to work only with following pattern (service name should always be identity):

api/identity/{anyController}/{id}

Now I could accomplish this by simply changing my route template to

routeTemplate: "api/identity/{controller}/{id}",

but then I would not be able to read "service_name" from Request.GetRouteData(); since it's not named parameter.

Is there a simpler way to do this, rather than creating an ActionFilter which will filter all requests who's service name is not "Identity" in this case.

4
  • Can not understand, if you change to "api/identity/{controller}/{id}" there is not service_name)) Commented Aug 29, 2016 at 8:31
  • @ElvinMammadov if you hardcode template to api/identity, when you try to check service_name in the RouteData dictionary, there is no entry with service_name key. Commented Aug 29, 2016 at 8:34
  • But instead using Route config, you can use Attribute Routing. It is good way that Route config. Commented Aug 29, 2016 at 8:34
  • Use RoutePrefix attribute above your Controller. like [RoutePrefix("api/identity")] and then use [Route("{id}")] above your Action. Its make your Url like api/identity/id?id= Commented Aug 29, 2016 at 10:24

1 Answer 1

2

You could add Route attribute above the method that is affected. For example,

[Route("api/identity/{controller}/{id}", Order = 1)]
[HttpGet]
public IHttpActionResult DoSomethingHere(int id)
{
    // Do some magic here
}

Have a look at this article Attribute Routing in ASP.NET Web API 2.

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

1 Comment

I was hoping to avoid attribute mess, but I guess it's a way to go

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.