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

Match any action in custom route


I need to create a custom route map that allows me to match any action in a certain url mapping. Example: www.site.com/patient/records/treatments/23 where treatments could be any action in the pacient controller.

Here's what i have try but doesnt work:

  routes.MapRoute("records_ho", "{controller}/records/{action}/{recordid}", new {
            controller = "patient", recordid = UrlParameter.Optional
        });

  routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Account", action = "User", id = UrlParameter.Optional }
            );

As you may have notice, i did not specify the action property in 'records_ho' and thats because I would like to avoid specifing in the MapRoute the 15 actions defined in the controller Pacient.

How can i achieve that?

Update: Here is the action

[HttpGet]
public ActionResult Treatments(string recordid)
{
    // some code here...


    return View(model);
}

Solution

  • In theory everything should be working as expected, see below.

    Code of the routing:

    using System.Web.Mvc;
    using System.Web.Routing;
    
    namespace WebApplication6
    {
        public class RouteConfig
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/records/{action}/{recordid}",
                    defaults: new { controller = "patient", recordid = UrlParameter.Optional }
                );
            }
        }
    }
    

    Code of the controller:

    using System.Web.Mvc;
    
    namespace WebApplication6.Controllers
    {
        public class PatientController : Controller
        {
            [HttpGet]
            public ActionResult Treatments(string recordid)
            {
                return View();
            }
        }
    }
    

    And the request/response:

    Request URL:http://localhost:29930/patient/records/treatments/23
    Request Method:GET
    Status Code:200 OK
    Remote Address:[::1]:29930
    Referrer Policy:no-referrer-when-downgrade
    Cache-Control:private
    Content-Encoding:gzip
    Content-Length:1538
    Content-Type:text/html; charset=utf-8
    Date:Fri, 21 Apr 2017 20:42:02 GMT
    Server:Microsoft-IIS/10.0
    Vary:Accept-Encoding
    X-AspNet-Version:4.0.30319
    X-AspNetMvc-Version:5.2
    X-Powered-By:ASP.NET