1

How can I simplify these routes?

config.Routes.MapHttpRoute(
    name: "GetUsersRoute",
    routeTemplate: "api/User",
    defaults: new { controller = "User", action = "GetUsers" }
);

config.Routes.MapHttpRoute(
    name: "GetUserRoute",
    routeTemplate: "api/User/{id}",
    defaults: new { controller = "User", action = "GetUser", id = RouteParameter.Optional }
);

config.Routes.MapHttpRoute(
    name: "GetEmailAddressRoute",
    routeTemplate: "api/User/GetEmailAddress/{id}",
    defaults: new { controller = "User", action="GetEmailAddress", id = RouteParameter.Optional }
);


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

I needed to add the GetEmailAddressRoute because the controller didn't know which action to take for a path like api/User/5. However, since then former routes like api/User don't lead to the correct action.

Some action signatures from the controller:

public Object GetUsers() { };

public Object GetUser(int id) { };

public HttpResponseMessage GetEmailAddress (int id) { };

But now I'd need to add another route for the Post actions. Is there a simpler way?

Update: What helped me for posting new users was to remove the action from the first route. Now it is

config.Routes.MapHttpRoute(
    name: "GetUsersRoute",
    routeTemplate: "api/User",
    defaults: new { controller = "User" }
);
1
  • 1
    I don't think that you need another route for post actions. I've never seen that done before, unless you are posting elsewhere. Try changing your default routeTemplate: "api/{controller}/{action}/{id}" Commented Nov 8, 2013 at 10:50

1 Answer 1

1

You can take advantage of the new routing attribute feature coming with web api 2 :

[Route("api/User")]
public Object GetUsers() { };

[Route("api/User/{id}")]
public Object GetUser(int id) { };

[Route("api/User/GetEmailAddress/{id}")]
public HttpResponseMessage GetEmailAddress (int id) { };
Sign up to request clarification or add additional context in comments.

1 Comment

you could use RoutePrefix to avoid repeating 'api/User'

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.