匹配自定义路由中的任何动作

Match any action in custom route

我需要创建一个自定义路由映射,使我能够匹配特定 url 映射中的任何操作。 示例:www.site.com/patient/records/treatments/23 其中 treatments 可以是 pacient 控制器中的任何操作。

这是我尝试过但不起作用的方法:

  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 }
            );

您可能已经注意到,我没有在 'records_ho' 中指定操作 属性 那是因为我想避免在 MapRoute 中指定控制器中定义的 15 个操作 Pacient.

我怎样才能做到这一点?

更新: 这是动作

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


    return View(model);
}

理论上一切都应该按预期工作,见下文。

路由代码:

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 }
            );
        }
    }
}

控制器代码:

using System.Web.Mvc;

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

和 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