2017-04-21 59 views
0

我需要創建一個自定義路由映射,使我能夠匹配某個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」和多數民衆行動的財產,因爲我想,以避免在圖路線specifing的在控制器Pacient中定義了15個動作。

我該如何做到這一點?

更新: 這裏是行動

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


    return View(model); 
} 
+0

@EugeneKomisare nko我對MapHttpRoute的api路由不太瞭解,但是,似乎是這樣。 –

+0

你測試了自己的路線嗎?剛剛嘗試過,在我身邊沒有任何問題,例如能夠呈現沒有問題的'/ patient/records/index/100'和'/ patient/records/contact/100'。你會得到什麼錯誤? –

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

我正在測試傳遞參數與?。這就是爲什麼它沒有加工任何東西。謝謝! –

+0

沒問題,與其他人分享問題總是有幫助! –