user789235
user789235

Reputation: 223

How do I map the root directory to a controller in c# using web api?

I have a c# web api (.net 4) web application. I have several controllers. I'd like to map a new controller to the root directory for the web app.

So, I have http://localhost/listproducts

I'd like the url to be http://localhost

But I don't know how to tell the controller to use the root directory. It seems to be configured based on the name.

The solution I went with is:

config.Routes.MapHttpRoute(
      name: "ListProductsApi",
             routeTemplate: "",
             defaults: new { controller = "ListProducts" } // Parameter defaults
);

The trick is the defaults: new { controller = "ListProducts" } line. (I need a POST action so I just left action out. Apparently when you want the root route "/" you need to explicitly name the controller.

Upvotes: 5

Views: 8003

Answers (2)

Ned Smajic
Ned Smajic

Reputation: 31

It should be fairly easy, just change a default route in your global.asax.cs and instead of

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

change it to

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "ListProducts", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

Upvotes: 3

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

You simply need to change the default route you already have. It should currently look something like this:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index",
                    id = UrlParameter.Optional }
);

Change controller = "Home" to controller = "listproducts".

Upvotes: 8

Related Questions