Asp.Net MVC路由引數獲取、替換

老廖發表於2019-05-11

 
        /// <summary>
        /// 獲取路由引數
        /// </summary>
        /// <param name="name">引數名</param>
        /// <returns></returns>
        public string Values(string name)
        {
            return this.RouteData.GetRequiredString(name);
        }

        /// <summary>
        /// 獲取路由引數
        /// </summary>
        /// <typeparam name="T">目標型別</typeparam>
        /// <param name="name">引數名</param>
        /// <param name="def">預設值</param>
        /// <returns></returns>
        public T Values<T>(string name, T def)
        {
            return ConvertUtility.ConvertTo(this.Values(name), def);
        }

        /// <summary>
        /// 獲取當前頁面路由地址
        /// </summary>
        /// <returns></returns>
        public string GetRouteUrl()
        {
            var route = this.RouteData.Route as Route;
            return route == null ? string.Empty : route.Url;
        }

        /// <summary>
        /// 獲取當前頁面路由地址並替換指定引數
        /// </summary>
        /// <param name="key">引數名</param>
        /// <param name="value">引數值(預設:{0},可用於頁面上快速替換)</param>
        /// <returns></returns>
        public string GetRouteUrl(string key, string value = "{0}")
        {
            string url = GetRouteUrl();
            return this.RouteData.Values.Aggregate(url, (current, pair) => current.Replace("{" + pair.Key + "}", pair.Key == key ? value : pair.Value.ToString()));
        }



老廖最後編輯於:4年前

內容均為作者獨立觀點,不代表八零IT人立場,如涉及侵權,請及時告知。

相關文章