How does one set the default controller to use when using AttributeRouting instead of the default RouteConfiguration that WebAPI uses. i.e. get rid of the commented code section since this is redundant when using AttribteRouting
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//routes.MapRoute(
// name: "Default",
// url: "{controller}/{action}/{id}",
// defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
//);
}
}
If I comment the section above and try to run the webapi app, I get the following error since there is no default Home controller/action defined. HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory.
How can I specify the route via Attribute routing for the Home controller/action?
EDIT: Code Sample:
public class HomeController : Controller
{
[GET("")]
public ActionResult Index()
{
return View();
}
public ActionResult Help()
{
var explorer = GlobalConfiguration.Configuration.Services.GetApiExplorer();
return View(new ApiModel(explorer));
}
}
The Route attribute can be applied on any controller or action method. In order to use attribute routing with Web API, it must be enabled in WebApiConfig by calling config. MapHttpAttributeRoutes() method.
The default route template for Web API is "api/{controller}/{id}".
UseEndpoints(endpoints => { endpoints. MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); Inside the call to UseEndpoints() , we use the MapControllerRoute() method to create a route by giving the name default .
This worked for me. Add this to Register()
in WebApiConfig
class
config.Routes.MapHttpRoute(
name: "AppLaunch",
routeTemplate: "",
defaults: new
{
controller = "Home",
action = "Get"
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With