Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 478
user789235 Avatar asked Oct 04 '12 15:10

user789235


1 Answers

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".

like image 124
Daniel Hilgarth Avatar answered Oct 12 '22 11:10

Daniel Hilgarth