Search code examples
c#asp.net-mvcasp.net-mvc-routing

Route prefix is not working with index


I have controller: DoomPlaceController

In route: I have used: doom-place/{parameter} // no action

and In controller :

[Route("doom-place/{parameter}")]
public ActionResult Index(string parameter)
{
    return View(); 
}

What I want: when I hit URL: www.xyz.com/doom-place it should open Doom-Place/index page.

But right now, I am able to access the page with doom-place/index but I want when I hit www.xyz.com/doom-place, it will automatically open index page.

Help will be appreciated.


Solution

  • You can make the parameter optional

    [RoutePrefix("doom-place")]
    public class DoomPlaceController : Controller {
        //Matches GET /doom-place
        //Matches GET /doom-place/some_parameter
        [HttpGet]
        [Route("{parameter?}")]
        public ActionResult Index(string parameter) { 
            return View(); 
        }
    }
    

    Given that attribute routing is being used, the assumption is that attribute routing has been enabled in RouteConfig.RegisterRoutes

    public static void RegisterRoutes(RouteCollection routes) {
        routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
    
        //enable attribute routing     
        routes.MapMvcAttributeRoutes();
    
        //covention-based routes
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
    

    Reference Attribute Routing in ASP.NET MVC 5