簡體   English   中英

C#MVC路由檢測

[英]C# MVC Route detection

我需要打電話給客戶資料頁面,例如“(www.mysite.com/John)或(www.mysite.com/customer name)”

所以我添加了這樣的路線

routes.MapRoute(
              name: "Profile",
              url: "{id}",
              defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
             );

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

但它總是走到第一條路線,好像我需要打開任何控制器它沒有任何建議嗎?

謝謝。

這條路線不會這樣,所以你有兩個選擇

1)當您采取任何行動時,您的URL應為www.mysite.com/controller/action ,否則會出現HTTP 404錯誤

2)您可以通過添加前綴www.mysite.com/Customer/John來使路由唯一

  routes.MapRoute(
     name: "Profile",
     url: "Customer/{id}",
     defaults: new { controller = "Home", action = "Index"}
     );

你的action應該是

public ActionResult Index(string id)
{
    string SurveyName = "";
    if (id != null)
        SurveyName = id;
    if (!string.IsNullOrEmpty(SurveyName))
    {
        ViewBag.Survey = SurveyName;
    }
    return View();
}

您需要根據您的要求更改controlleraction ,您仍然為controlleraction提供默認值。

您也可以使用Html.ActionLink來參考您想要的視圖。 Html.ActionLink("action_name","Controller_name")

您的路線有一個可選參數,並且像捕捉所有路線一樣工作。

[編輯]如果您沒有限制路線的模式,則不能像我之前的答案中所說的那樣使用約束。 基於此,您可以從默認值中刪除id = UrlParameter.Optional (通過此更改,只有當url包含id參數時才會到達您的路由)。

            routes.MapRoute(
                      name: "Profile",
                      url: "{id}",
                      defaults: new { controller = "Employee", action = "Index"}
                     );

另一個選擇是創建一個自定義路由約束來檢查你的配置文件ID是否有效,但要小心,因為它會降低你的應用程序,因為它將在每個請求上執行(可能緩存你的配置文件列表可能有助於此)。

[OLD ANSWER]限制路徑范圍的一種簡單方法是使用約束。

如果id參數是4位數值(您可以使用自己的正則表達式來滿足您的要求),則會達到以下路線。

            routes.MapRoute(
                      name: "Profile",
                      url: "{id}",
                      defaults: new { controller = "Employee", action = "Index"},
                      constraints: new { id = @"\d{4}" }
                     );

進行這些更改。 它對我有用。

routes.MapRoute(
              name: "Profile",
              url: "{id}",
              defaults: new { controller = "NewCon", action = "Demo", id = UrlParameter.Optional }
             );

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM