Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding sub folders in the controller folder - .net webapi

Is there a way to add sub folders in the Controller folder of a Webapi project?

I'm thinking of something like Controller/Customer includes the controllers for the Customer module.

like image 438
mangun Avatar asked Dec 04 '12 08:12

mangun


4 Answers

Controllers don't work in that way. In Asp.NET your folder structure is your website structure. In WEB API, controllers are looked for independently of the structure. As a matter of fact, you can have them in different assembly and they still will be found by the framework. The routing will not work the way you expect. You can add a route where you have your "folder name", like you said, localhost/WebApp/{foldername}/{controller}. Only {foldername} can be plain, static folder name (localhost/WebApp/foldername/{controller}). So the client will have to call url with "foldername" in it but the location of code wouldn't matter because MVC framework doesn't differentiate folder trees under controllers.

like image 118
T.S. Avatar answered Nov 09 '22 10:11

T.S.


The answers here are wrong. You can easily do this. You just need to then specify the route on your controller class:

Located in /Controllers/Authentication folder

//An example of you specifying a diff. route than the folder path
[Route("api/login")]
public class LoginController {...}
like image 35
Don Rhummy Avatar answered Nov 09 '22 10:11

Don Rhummy


I used areas to solve this problem. As specified here http://blogs.infosupport.com/asp-net-mvc-4-rc-getting-webapi-and-areas-to-play-nicely/

like image 40
mangun Avatar answered Nov 09 '22 10:11

mangun


What I do to solve this issue for my self is adding another Maproute and add namespace before the controller. Just be aware of two points:

  1. Your new rout should be before the Default one
  2. You cannot add the namespace for the default one

        routes.MapRoute(
           name: "Secretariat",
           url: "{namespace}/{controller}/{action}/{id}",
           defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
       );
    
like image 26
Omid Naghizadeh Avatar answered Nov 09 '22 09:11

Omid Naghizadeh