第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么要在ASP.NETMVC中的公共路由之前先映射特殊路由?

為什么要在ASP.NETMVC中的公共路由之前先映射特殊路由?

天涯盡頭無女友 2019-06-21 13:25:02
為什么要在ASP.NETMVC中的公共路由之前先映射特殊路由?來自萬維網(wǎng):.路由引擎將選擇與所提供的URL匹配的第一條路由,并嘗試在該路由中使用路由值。因此,應(yīng)該先將不太常見或更專門化的路由添加到表中,而更一般的路由則應(yīng)在稍后添加.為什么我要先繪制專用線呢?有人可以給我舉個例子,在哪里我可以看到“地圖公共路線第一”的失???
查看完整描述

1 回答

?
慕萊塢森

TA貢獻(xiàn)1810條經(jīng)驗 獲得超4個贊

路由引擎將選擇與提供的URL匹配的第一條路由,并嘗試在該路由中使用路由值。

發(fā)生這種情況的原因是RouteTable被用作開關(guān)箱語句。圖如下:

int caseSwitch = 1;switch (caseSwitch){
    case 1:
        Console.WriteLine("Case 1");
        break;
    case 1:
        Console.WriteLine("Second Case 1");
        break;
    default:
        Console.WriteLine("Default case");
        break;}

如果caseSwitch1,第二個塊永遠(yuǎn)不會到達(dá),因為第一個塊捕獲了它。

Route類遵循類似的模式(在GetRouteDataGetVirtualPath方法)。他們可以返回兩個州:

  1. 一組路由值(或

    VirtualPath

    對象的

    GetVirtualPath

    )。這表示與請求匹配的路由。
  2. null

    ..這表明路由與請求不匹配。

在第一種情況下,mvc使用路由生成的路由值來查找Action方法。在這種情況下,RouteTable沒有進(jìn)一步分析。

在第二個例子中,mvc將檢查下一個RouteRouteTable要查看它是否與請求匹配(內(nèi)置行為與URL和約束匹配,但技術(shù)上可以匹配HTTP請求中的任何內(nèi)容)。再一次,該路線可以返回一組RouteValuesnull取決于結(jié)果。

如果您嘗試像上面那樣使用一個Switch-case語句,程序?qū)⒉粫幾g.但是,如果您配置的路由絕不可能回報null或返回RouteValues對象在更多情況下,程序?qū)⒕幾g,但會出現(xiàn)錯誤行為。

錯誤配置示例

下面是我經(jīng)常在StackOverflow(或它的某些變體)上看到的典型例子:

public class RouteConfig{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

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

在本例中:

  1. CustomRoute

    將匹配任何長度為1、2或3段的URL(注意,

    segment1

    是必需的,因為它沒有默認(rèn)值)。
  2. Default

    將匹配任何長度為0、1、2或3段的URL。

因此,如果應(yīng)用程序被傳遞,則URL\Home\About,CustomRoute將匹配,并提供以下內(nèi)容RouteValues轉(zhuǎn)到MVC:

  1. segment1 = "Home"

  2. controller = "MyController"

  3. action = "About"

  4. id = {}

這將使mvc尋找一個名為About在一個名為MyControllerController如果它不存在就會失敗。這個Default在這種情況下,路由是一個無法到達(dá)的執(zhí)行路徑,因為即使它將匹配一個2段URL,框架也不會給它機(jī)會,因為第一次匹配獲勝。

修復(fù)配置

關(guān)于如何繼續(xù)修復(fù)配置,有幾個選項。但所有這些都取決于第一場比賽獲勝然后路由就不會再看下去了。

選項1:添加一個或多個文字段

public class RouteConfig{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "CustomRoute",
            url: "Custom/{action}/{id}",

            // Note, leaving `action` and `id` out of the defaults
            // makes them required, so the URL will only match if 3
            // segments are supplied begining with Custom or custom.
            // Example: Custom/Details/343
            defaults: new { controller = "MyController" }
        );

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

選項2:添加1個或更多RegEx約束

public class RouteConfig{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "CustomRoute",
            url: "{segment1}/{action}/{id}",
            defaults: new { controller = "MyController", action = "Index", id = UrlParameter.Optional },
            constraints: new { segment1 = @"house|car|bus" }
        );

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

選項3:添加1個或更多自定義約束

public class CorrectDateConstraint : IRouteConstraint{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName,
    RouteValueDictionary values, RouteDirection routeDirection)
    {
        var year = values["year"] as string;
        var month = values["month"] as string;
        var day = values["day"] as string;

        DateTime theDate;
        return DateTime.TryParse(year + "-" + month + "-" + day, System.Globalization.CultureInfo.InvariantCulture,
         DateTimeStyles.None, out theDate);
    }}public class RouteConfig{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "CustomRoute",
            url: "{year}/{month}/{day}/{article}",
            defaults: new { controller = "News", action = "ArticleDetails" },
            constraints: new { year = new CorrectDateConstraint() }
        );

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

備選案文4:使所需段+使段數(shù)與現(xiàn)有路由不匹配

public class RouteConfig{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "CustomRoute",
            url: "{segment1}/{segment2}/{action}/{id}",
            defaults: new { controller = "MyController" }
        );

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

在上述情況下,CustomRoute將只匹配一個URL與4個段(注意,這些可以是任何值)。這個Default像以前一樣,路由只匹配0、1、2或3段的URL。因此,沒有無法到達(dá)的執(zhí)行路徑。

選項5:為自定義行為實現(xiàn)RouteBase(或路由)

路由不支持開箱即用的任何東西(例如特定域或子域上的匹配)都可以通過實現(xiàn)你自己的RouteBase子類或者路線子類。這也是理解路由工作方式的最佳方法。

public class SubdomainRoute : Route{
    public SubdomainRoute(string url) : base(url, new MvcRouteHandler()) {}

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var routeData = base.GetRouteData(httpContext);
        if (routeData == null) return null; // Only look at the subdomain if this route matches in the first place.
        string subdomain = httpContext.Request.Params["subdomain"]; 
        // A subdomain specified as a query parameter takes precedence over the hostname.
        if (subdomain == null) {
            string host = httpContext.Request.Headers["Host"];
            int index = host.IndexOf('.');
            if (index >= 0)
                subdomain = host.Substring(0, index);
        }
        if (subdomain != null)
            routeData.Values["subdomain"] = subdomain;
        return routeData;
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        object subdomainParam = requestContext.HttpContext.Request.Params["subdomain"];
        if (subdomainParam != null)
            values["subdomain"] = subdomainParam;
        return base.GetVirtualPath(requestContext, values);
    }}

這個班是從下列地方借來的:是否可以基于子域創(chuàng)建ASP.NETMVC路由?

public class RouteConfig{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.Add(new SubdomainRoute(url: "somewhere/unique"));

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

注:這里真正的問題是,大多數(shù)人認(rèn)為他們的路線都應(yīng)該看起來像Default路線。收到,粘貼,完成,對吧?不對。

這種方法通常會產(chǎn)生兩個問題:

  1. 幾乎所有其他路由都應(yīng)該至少有一個文字段(如果您喜歡這類內(nèi)容,則應(yīng)該有一個約束)。
  2. 最符合邏輯的行為通常是使其他路線具有

    所需

    片段。

另一個常見的誤解是,可選段意味著您可以省略。任何段,但在現(xiàn)實中,您只能離開最右邊的一段或幾段。

微軟成功地實現(xiàn)了基于路由約定的、可擴(kuò)展的和強(qiáng)大的路由協(xié)議.他們沒能直觀地理解。幾乎每個人第一次嘗試都失敗了(我知道我成功了!)幸運(yùn)的是,一旦你了解了它的工作原理,就不難了。


查看完整回答
反對 回復(fù) 2019-06-21
  • 1 回答
  • 0 關(guān)注
  • 399 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號