匹配自定义路线中的任何操作

时间:2017-04-21 19:51:35

标签: c# asp.net-mvc url routing asp.net-mvc-routing

我需要创建一个自定义路由映射,允许我匹配某个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'中指定action属性,因为我想避免在MapRoute中指定控制器Pacient中定义的15个动作。

我如何实现这一目标?

更新: 这是行动

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


    return View(model);
}

1 个答案:

答案 0 :(得分:1)

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

路由代码:

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 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