1

From what I understand, the route map with the format

            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }

maps the url "/api/file/1" to the controller "FileController" and the GET method contained within that controller which accepts a string input called "id". Similarly, if I had the url "/api/meeting/1", it would map to the controller "MeetingController" and the GET method accepting a string input called "id".

Is it possible to have both of the above two, instead, map to the same controller?

IE, can I somehow set up a "DefaultController", which takes the URL "/api/file/1", and maps it to a method called "GetData(string id)"? And then within that method, can I somehow obtain the "file" part?

The reason I ask this is because the "FileController" and "MeetingController" described above would, in implementation, be identical. The only difference would be that the parameter passed to the function which I use to get my data, would change from "file" to "meeting".

1 Answer 1

1

Your route:

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

Your controller:

public class GenericController : ApiController
{
    [HttpGet]
    public string GenericAction(string data, int? id)
    {
        return data + "-" + id.ToString();
    }
}

This http://localhost:53221/api/files/1 will return (if you accept xml)

string>files-1</string>

That said,I don't think what you are trying to do makes sense.
If your controllers are similar use a base class

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

2 Comments

That works perfectly. Thanks! But what do you mean by "use a base class"?
@KiranRamaswamy Use a base class for your controllers so you can reuse as much code as possible

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.