Search code examples
asp.net-mvcroutesasp.net-mvc-routing

URL Route for all controllers of a folder as an API in MVC .Net core


I have to define following on all web API.

[Route("api/[controller]")]

How can I define this as default which is in particular folder.

Let's say I have folder API. in which I want to set these attributes (or don't want to write) on all controllers of that folder.

How to define this sort of route in .Net core MVC?


Solution

  • Goto App_Start folder WebApiConfig.cs and put this code there, So it will be applied globally for all the controllers and action methods. You can invoke this in project like http://localhost/API/ControllerName/MethodName?parameters

        config.Routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
        config.Routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
        config.Routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
        config.Routes.MapHttpRoute("DefaultApiPost", "Api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });